In my game I have both characters and enemies who need to look the direction they move in. It is in almost every game so I don’t know why I’m struggling so hard to find the correct way to do this. This is my player script:
public float speed;
private float MoveVertical;
private float MoveHorizontal;
void Update () {
MoveHorizontal = Input.GetAxis ("Horizontal");
MoveVertical = Input.GetAxis ("Vertical");
Vector2 Movement = new Vector2 (MoveHorizontal, MoveVertical);
GetComponent<Rigidbody2D>().velocity = Movement * speed;
and this is the enemy:
void Update () {
enemydistanceX = Mathf.Abs (target.position.x - transform.position.x);
enemydistanceY = Mathf.Abs (target.position.y -transform.position.y);
if (enemydistanceX < enemydistanceallowance && enemydistanceY < enemydistanceallowance){
transform.up = -target.position - transform.position;
This is some code for 8-directional movement with facing the direction of movement…
public class Test3 : MonoBehaviour
{
[SerializeField]
Rigidbody2D rb;
public float speed = 2;
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 move;
move.x = h;
move.y = v;
move.z = 0;
move.Normalize();
if (h != 0 || v != 0) transform.right = move;
move *= speed;
rb.velocity = move;
}
}
Hope that helps some.
2 Likes
Wow! That’s brilliant! thank you! but secondary question, how can I make it more fluid? Also what is the purpose of Normalize here?
Also why does your ‘if’ statement not need curly brackets after, don’t they always go
If (true of false statement){thing that happens}
When there is only 1 statement, the braces are optional.
It means if you had 1 up and 1 left, it would make the magnitude only 1 (so you wouldn’t go faster diagonally, for instance).
As for how to make it more fluid, that depends on if you mean:
- it gradually turns
- you can face more than 8 directions.
For 1, you can store the rotation/direction in a variable, and gradually turn towards it over time.
For 2, you’d have to alter the code somewhat. It could be several variations and I can’t just write it up right this second…
