# Instantly snap into specific directions?

In my 2d setup, I want the player to constantly move in a specific direction at a set speed. It's similar to "Snake" in that you can only move in four directions and you can't stop your movement.

Right now, the way I do this is by having a char variable "direction", which can either be u, d, l, r (take a guess what those stand for). Based on those letters, I use GetComponent().MovePosition and increase/decrease the position on the x or y axis.

Is there a better way to do this? I would prefer if I could just enter the degree (0, 90, 180, 270) to make the player move in the right direction. I tried AddForce but I couldn't get it to work.

Side note: it's important for me that I can set the direction without player input, as there are some objects that force the player into a different direction.

Edit: As the tag would suggest, I'm looking for a Unity specific answer, as I'm not sure which function would best suit my needs.

• Possible duplicate of How do I make an entity move in a direction? – Bálint Oct 25 '18 at 22:47
• @Bálint I fail to see how that's relevant to my Unity specific question. Maybe to explain the concept, but I'd like to know how it's done in Unity. – noClue Oct 25 '18 at 23:00

Here's a solution I found thanks to help from @cmprogram.

Rotating the object:

rb.eulerAngles = new Vector3(0, 0, angle);


Making the object move in the new direction inside FixedUpdate:

rb.velocity = rb.right * speed * Time.fixedDeltaTime;


Very simple.