Transform.Forward help
How do i correctly use transform.forward? Not exactly clear on how this works, Ive successfully made instigated objects face the mouse direction, but do not know the correct code to make them move in the direction they are facing.
Right now, i am using
transform.position = new Vector2(xposV + 1, yposV + 0);
However, i want the spawned projectile to instead move in the direction it is currently facing rather than directly to the right. How do i do this?
i tried transform.position = transform.forward * 3;
but honestly i have no idea how it is supposed to work.
Oh, also i am working in unity 2D.
Thanks in advance.
Answer by $$anonymous$$ · Feb 21, 2017 at 02:52 AM
Transform.forward is a direction, one of the many uses of Vector3's (to my understanding). If you want to use it to move an object in the direction it's facing, the code would look something like this:
// Notice the += instead of =
transform.position += transform.forward * Time.deltaTime;
In order for this to work properly, you also need to set the objects rotation to the direction you want to move. So play around with rotations if it still doesn't move the way you want. You may need a rotation offset, but I haven't worked much with 2D games. The blue arrow represents the Transform's forward when the box in the top left of the editor reads "Local" (Compared to "Global")
The Time.deltaTime just makes it so that it will move in meters per second (or whatever units you are using). I'm not sure if you've used this before, but this will only work inside of an Update method or something that is like it (this is important). If the method you're using is FixedUpdate (for physics), then use Time.fixedDeltaTime.
In case you haven't seen a Vector3 (or Vector2) used as a direction, it's a position with a magnitude (length) of one and its super useful. This video by Unity explains them well.
Apologies if I over-explained anything. Just not sure how much you have used Unity.
I hope this helped!