How to to better Unity 2D movement

As I started developing games with the Unity Gameengine I used a very simple and straight forward methode to move entities arround. But that one was wrong. Until recently all my motion and placement of Unity Gameobject was handled as follows.

Part of the class "EnemyBeheaviour" In AI-Buster WRONG!
private void MoveToPlayer()
{
	Vector3 distance = player.transform.position - middlePointEnemy.position;

	if(Mathf.Abs(distance.x) > 0.3f){
		flipped = distance.x < 0.1f;
	}
	transform.position += (player.transform.position - transform.position).normalized * (movementSpeed * Time.deltaTime);
}

Much better It would be to use the rigidbody. In most of the cases you have anyway already attached a Rigidbody2D to your gameobject and it it is used for collision detection. If you simple move the transform arround, the collision detection can (and in some cases will) get confused. To avoid that add your Position to the rigidbody. Do this not by "rigidbody2d.position = xxx" but instead by "Rigidbody2d.MovePosition(new Vector3(/*new position*/)").

Part of the class "EnemyBeheaviour" In AI-Buster As it should be done!
private void MoveToPlayer()
{
	Vector3 distance = player.transform.position - middlePointEnemy.position;

	if(Mathf.Abs(distance.x) > 0.3f){
		flipped = distance.x < 0.1f;
	}
	rigidbody2d.MovePosition(transform.position + (player.GetComponent:Rigidbody2D:().position - transform.position).normalized * (movementSpeed * Time.deltaTime));
}

Setting up the Rigidbody

The here shown setup might not be correct in your project.

More on Rigidbodies and Movement in Unity

In this section I listed two usefull links which explain further how to master Unity movement. Check out This Unity answer or the attached youtube video of brackeys.

By the way

Checkout AI-Buster in the Google Playstore as I released it with this new version just now


Get It here

Back to Dev-Log