- Home /
Move towards current direction on the Z axis (2D)
Hello,
I'm making a 2D game where you turn with A and D and go forward with W. I managed to get the rotating working but I can't find out how to move towards the direction the object is facing.
#pragma strict
var turnright : KeyCode;
var turnleft : KeyCode;
var fwards : KeyCode;
var mspeed = 6;
function Update () {
// rigidbody2D.velocity =new Vector2(Input.GetAxis("Horizontal") * mspeed, Input.GetAxis("Vertical") * mspeed);
if (Input.GetKey(turnleft))
{
transform.Rotate(Vector3.forward * 1);
}
if (Input.GetKey(turnright))
{
transform.Rotate(Vector3.back * 1);
}
if (Input.GetKey(fwards))
{
}
}
turnright is set to D turnleft is set to A fwards is set to W
How can I make my object move towards the direction it is facing with speed = mspeed?
Answer by tanoshimi · Jun 29, 2014 at 10:04 PM
transform.position += transform.forward * mspeed;
Even though that is correct, I would multiply by a time. http://docs.unity3d.com/ScriptReference/Time-deltaTime.html
It worked but I had to change forward to up, my bad. Added Time.deltaTime to the code but I had to set some parameters fairly high to make it work the way I want:
if (Input.Get$$anonymous$$ey(turnleft))
{
transform.Rotate(Vector3.forward * Time.deltaTime * 200);
}
if (Input.Get$$anonymous$$ey(turnright))
{
transform.Rotate(Vector3.back * Time.deltaTime * 200);
}
if (Input.Get$$anonymous$$ey(fwards))
{
transform.position += transform.up * Time.deltaTime * 4;
}
Result is that when I "walk" with the object against a collider, the object does not stop from moving like first, but humps against the collider like a horny dog. What is up with that? Did I use Time.deltaTime the wrong way?
Your answer
Follow this Question
Related Questions
2D AI flipping 90 degrees Yaxis in play mode, weird hopping glitch? 0 Answers
object rotates toward mouse? 2D Top Gameplay 6 Answers
Angle to Rotation 2 Answers