- Home /
Objekt soll Vorwärts gehen, wenn es sich dreht
Hallo,
ich bin neu hier und ich habe eine Frage und zwar mein Code ist:
void Update() {
....
if (Input.GetKey(KeyCode.W)) pos.z += V * Time.deltaTime;
if (Input.GetKey(KeyCode.LeftArrow)) { pos.x -= 0.5f * Time.deltaTime; }
....
}
Jetzt ist meine Frage, wie ändere ich den Code so um, dass wenn sich das Objekt dreht, sodass sich dieses nach dem drehen vorwärts bewegt. Das heißt wenn ich die Taste W und dann LeftArrow ( 180 Grad Drehung) drücke und sich dann das Objekt dreht, dass dann sich das Objekt anstatt nach Hinten nach vorne bewegt und das in egal welche Richtung ich gerade bin.
P.S. Schonmal danke im voraus
From Google Translate: Now my question is, how do I change the code so that when the object rotates, it moves forward after being rotated. That means if I press the W key and then LeftArrow (180 degrees rotation) and then the object rotates, then the object moves forward rather than backward, no matter which direction I'm in.
Answer by Kciwsolb · Jun 08, 2018 at 05:47 PM
For moving on z (forward), try using something like:
transform.position = transform.position + transform.forward * V * Time.deltaTime; //Im assuming "V" is a speed float value
For moving on x (left and right) do the same, but use transform.right instead. For example, to move right:
transform.position = transform.position + transform.right * 0.5f * Time.deltaTime;
To move left, do the same except use -transform.right.
transform.forward, right, etc are all relative to how you are rotated. So, this will let you move forward even when you turn.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
I need a grid of objects at runtime, but the gameObject is instantiated later 0 Answers
counting of two different objects 0 Answers