Sanjay Madhav 8 лет назад
Родитель
Сommit
c2b313d32f
3 измененных файлов с 25 добавлено и 6 удалено
  1. 19 3
      Chapter05/Actor.cpp
  2. 4 3
      Chapter05/Actor.h
  3. 2 0
      Chapter05/Component.h

+ 19 - 3
Chapter05/Actor.cpp

@@ -17,6 +17,7 @@ Actor::Actor(Game* game)
 	,mScale(1.0f)
 	,mRotation(0.0f)
 	,mGame(game)
+	,mRecomputeWorldTransform(false)
 {
 	mGame->AddActor(this);
 }
@@ -36,8 +37,12 @@ void Actor::Update(float deltaTime)
 {
 	if (mState == EActive)
 	{
+		ComputeWorldTransform();
+
 		UpdateComponents(deltaTime);
 		UpdateActor(deltaTime);
+
+		ComputeWorldTransform();
 	}
 }
 
@@ -73,9 +78,20 @@ void Actor::ActorInput(const uint8_t* keyState)
 
 void Actor::ComputeWorldTransform()
 {
-	mWorldTransform = Matrix4::CreateScale(mScale);
-	mWorldTransform *= Matrix4::CreateRotationZ(mRotation);
-	mWorldTransform *= Matrix4::CreateTranslation(Vector3(mPosition.x, mPosition.y, 0.0f));
+	if (mRecomputeWorldTransform)
+	{
+		mRecomputeWorldTransform = false;
+		// Scale, then rotate, then translate
+		mWorldTransform = Matrix4::CreateScale(mScale);
+		mWorldTransform *= Matrix4::CreateRotationZ(mRotation);
+		mWorldTransform *= Matrix4::CreateTranslation(Vector3(mPosition.x, mPosition.y, 0.0f));
+
+		// Inform components world transform updated
+		for (auto comp : mComponents)
+		{
+			comp->OnUpdateWorldTransform();
+		}
+	}
 }
 
 void Actor::AddComponent(Component* component)

+ 4 - 3
Chapter05/Actor.h

@@ -38,11 +38,11 @@ public:
 
 	// Getters/setters
 	const Vector2& GetPosition() const { return mPosition; }
-	void SetPosition(const Vector2& pos) { mPosition = pos; ComputeWorldTransform(); }
+	void SetPosition(const Vector2& pos) { mPosition = pos; mRecomputeWorldTransform = true; }
 	float GetScale() const { return mScale; }
-	void SetScale(float scale) { mScale = scale;  ComputeWorldTransform(); }
+	void SetScale(float scale) { mScale = scale;  mRecomputeWorldTransform = true; }
 	float GetRotation() const { return mRotation; }
-	void SetRotation(float rotation) { mRotation = rotation;  ComputeWorldTransform(); }
+	void SetRotation(float rotation) { mRotation = rotation;  mRecomputeWorldTransform = true; }
 	
 	void ComputeWorldTransform();
 	const Matrix4& GetWorldTransform() const { return mWorldTransform; }
@@ -67,6 +67,7 @@ private:
 	Vector2 mPosition;
 	float mScale;
 	float mRotation;
+	bool mRecomputeWorldTransform;
 
 	std::vector<class Component*> mComponents;
 	class Game* mGame;

+ 2 - 0
Chapter05/Component.h

@@ -21,6 +21,8 @@ public:
 	virtual void Update(float deltaTime);
 	// Process input for this component
 	virtual void ProcessInput(const uint8_t* keyState) {}
+	// Called when world transform changes
+	virtual void OnUpdateWorldTransform() { }
 
 	int GetUpdateOrder() const { return mUpdateOrder; }
 protected: