Draw entities with a protocol instead of a multi-method

This commit is contained in:
oakes
2014-03-15 20:29:36 -04:00
parent 8544ab94b6
commit 07c296fee6
3 changed files with 70 additions and 68 deletions

View File

@@ -1,8 +1,8 @@
(ns play-clj.utils
(:require [clojure.string :as s])
(:import [com.badlogic.gdx.graphics.g2d NinePatch ParticleEffect
(:import [com.badlogic.gdx.graphics.g2d NinePatch ParticleEffect SpriteBatch
TextureRegion]
[com.badlogic.gdx.graphics.g3d ModelInstance]
[com.badlogic.gdx.graphics.g3d Environment ModelBatch ModelInstance]
[com.badlogic.gdx.scenes.scene2d Actor]
[com.badlogic.gdx.utils Array ArrayMap]))
@@ -172,7 +172,53 @@ new object to be created each time a field is set)
[object k & options]
`(call! ^ArrayMap ~object ~k ~@options))
; entities
; entity protocol/records
(defprotocol Entity
"Internal use only"
(draw-entity! [this batch] "Draws the entity"))
(defrecord TextureEntity [object] Entity
(draw-entity! [{:keys [^TextureRegion object x y width height]} batch]
(let [x (float (or x 0))
y (float (or y 0))
width (float (or width (.getRegionWidth object)))
height (float (or height (.getRegionHeight object)))]
(.draw ^SpriteBatch batch object x y width height))))
(defrecord NinePatchEntity [object] Entity
(draw-entity! [{:keys [^NinePatch object x y width height]} batch]
(let [x (float (or x 0))
y (float (or y 0))
width (float (or width (.getTotalWidth object)))
height (float (or height (.getTotalHeight object)))]
(.draw object ^SpriteBatch batch x y width height))))
(defrecord ParticleEffectEntity [object] Entity
(draw-entity! [{:keys [^ParticleEffect object x y delta-time]} batch]
(let [x (float (or x 0))
y (float (or y 0))
delta-time (float delta-time)]
(.setPosition object x y)
(.draw object ^SpriteBatch batch delta-time))))
(defrecord ActorEntity [object] Entity
(draw-entity! [{:keys [^Actor object] :as entity} batch]
(doseq [[k v] entity]
(case k
:x (.setX object v)
:y (.setY object v)
:width (.setWidth object v)
:height (.setHeight object v)
nil))
(.draw object ^SpriteBatch batch 1)))
(defrecord ModelEntity [object] Entity
(draw-entity! [{:keys [^ModelInstance object]}
{:keys [^ModelBatch renderer ^Environment attributes]}]
(.render renderer object attributes)))
; create-entity
(defmulti create-entity
"Internal use only"
@@ -180,20 +226,20 @@ new object to be created each time a field is set)
(defmethod create-entity TextureRegion
[obj]
{:type :texture :object obj})
(TextureEntity. obj))
(defmethod create-entity NinePatch
[obj]
{:type :nine-patch :object obj})
(NinePatchEntity. obj))
(defmethod create-entity ParticleEffect
[obj]
{:type :particle-effect :object obj})
(ParticleEffectEntity. obj))
(defmethod create-entity Actor
[obj]
{:type :actor :object obj})
(ActorEntity. obj))
(defmethod create-entity ModelInstance
[obj]
{:type :model :object obj})
(ModelEntity. obj))