- Home /
2D TOP DOWN - W A S D as direction
Hello I need here really a help
I am making a top down 2d tank shooter game. The direction should based on keys WASD. So if I want to go right the Z rotiation should be zero. If I go to left so it should be 270. So I don't know really how to calculate it. Because the Quaternion gives me headache.
When I used old engine it was without Quaternion. I just made Direction.ToAngle() and I got the angle were I could use .setAngle(angle). For smooth I just did SmoothAng = currentAng - (angle - CurrentAng) *0.1f (it hadn't lerp) In Unity it needs to Vectors to get an angle which confusing me while in old engine I used just one Vector like Quaternion.Euler.
Quaternion seems more complex. There is LookRotation or something else. Don't know really how these do the culculation. So I hope you can help me :S
Important!! It needs to be a smooth rotation.
Answer by robertbu · Jul 11, 2014 at 09:20 PM
While this can easily be done with Quaternions, it also can be easily done just using eulerAngles. Given you are rotating around 'y' axis, you can do something like this:
#pragma strict
var speed = 3.0;
private var angleTo = 0.0;
private var angle = 0.0;
function Update() {
if (Input.GetKeyDown(KeyCode.A))
angleTo = -90.0;
if (Input.GetKeyDown(KeyCode.S))
angleTo = 180.0;
if (Input.GetKeyDown(KeyCode.D))
angleTo = 90.0;
if (Input.GetKeyDown(KeyCode.W))
angleTo = 0.0;
angle = Mathf.Lerp(angle, angleTo, Time.deltaTime * speed);
transform.eulerAngles = Vector3(0.0, angle, 0.0);
}
A couple things to note here. First, I never read from eulerAngles. I keep my own variable (angle) and just write to them. Second, I'm using Time.deltaTime instead of 0.1. Since the time of each frame varies, you cannot used a fixed value in Update(). You could use a fixed value if you wanted to use FixedUpdate().
Answer by IKDev · Aug 24, 2020 at 07:20 PM
Well, I think this is solution (sorry because it is in C#):
rb.MovePosition(rb.position + new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")) * [speed of character, for example 5] * Time.fixedDeltaTime);