- Home /
How can i make a sprite move in the direction it is rotated?
I have a bullet and some code for turning it towards the player when it is instaniated, but i can't fiqure out how to make it move in the same direction as it is turned, up on the sprite is what i want to go forward.
public Transform targetTransform;
public Rigidbody2D rb;
public Transform _dart;
private Vector2 darttoo;
private Vector2 dartfrom;
private void Start()
{
// where i want it to go from an too, inn vector if i need it, needed it for one of the ways i
//tried it but it didnt work
Vector2 darttoo = new Vector2 (targetTransform.position.x, targetTransform.position.y);
Vector2 dartfrom = new Vector2 (_dart.position.x, _dart.position.y);
//just some stuff to make it not glitch out
Vector3 temp = new Vector3(0, 0, -2.988281f);
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
Vector3 relativePos = targetTransform.position - transform.position;
float angle = Mathf.Atan2(relativePos.y, relativePos.x) * Mathf.Rad2Deg - 90;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = q;
}
void Update()
{
}
}
Answer by lodendsg · Nov 19, 2019 at 05:33 PM
Assuming your rotating it such that its forward is facing its target then you can simply take its transform.forward as its direction.
e.g.
transform.position += transform.forward;
The above will move the transform forward by 1 unit regardless of the direction its facing.
More info here https://docs.unity3d.com/ScriptReference/Transform-forward.html
As you are working in 2D then you dont want forward you likey want right or up ... these are there as well e.g.
Right = https://docs.unity3d.com/ScriptReference/Transform-right.html
Up = https://docs.unity3d.com/ScriptReference/Transform-up.html
Thank you, that worked perfectly and is really simpel, but do you know how i would change the speed?
Hey xxmassassenxx. You can do
Vector3 _multiplyVelocity = new Vector3("x multiplier" * Time.deltaTime, "y multiplier" * Time.deltaTime, "z multiplier" * Time.deltaTime);
transform.position += Vector3.Scale(transform.position, _multiplyVelocity);
Replacing the string values with float type numbers!
That snippet is also multiplying the velocity of the body for Time.deltaTime
, which is certainly important for keeping the ratio of movement on each frame, and avoiding your player to do strange stuff on update.
simply scale it by the desired speed e.g.
float speed = 2;
transform.position += transform.forward * speed * Time.deltaTime;