- Home /
Move object forward relatively to itself
I've got this code, which should rotate the object and move it forward each frame. The problem is it doesn't move always forward but sometimes back or to the side. I think the problem is actually rotation and not translation.
void Update () {
if (Input.GetKey (KeyCode.RightArrow)) {
transform.localRotation = Quaternion.Euler(0, 90, 0);
}
if (Input.GetKey (KeyCode.DownArrow)) {
transform.localRotation = Quaternion.Euler(0, 180, 0);
}
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.localRotation = Quaternion.Euler(0, 270, 0);
}
if (Input.GetKey (KeyCode.UpArrow)) {
transform.localRotation = Quaternion.Euler(0, 0, 0);
}
transform.Translate (transform.forward * Time.deltaTime);
}
Answer by Xtro · Mar 12, 2014 at 02:13 PM
Can you try this instead,
transform.position += transform.forward * Time.deltaTime;
Strangely, this works. But I've read somewhere that directly setting position of an object is bad practice because there might be problems with hit detection.
Hit detection in Unity has always problems. It's a different issue. I never use translate method. I always modify the position and never had an issue.
Answer by ricardomaroquio · Aug 31, 2018 at 02:47 PM
The best and simple way I found to do it, always moving forward according to object face is using the code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour {
public float speed = 0;
private void FixedUpdate()
{
transform.Translate(0, 0, speed * Time.deltaTime, Space.Self);
}
void Update () {
if (Input.GetKey(KeyCode.UpArrow))
{
speed++;
}
if (Input.GetKey(KeyCode.DownArrow))
{
speed--;
}
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(0, -1, 0);
}
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(0, 1, 0);
}
}
}
I hope it helps.
Answer by flappyplan · Dec 25, 2018 at 06:20 PM
this is because transform.Translate implementation but if you use Vector3.forward they work fine like this transform.Translate (vector3.forward * Time.deltaTime);
Your answer
![](https://koobas.hobune.stream/wayback/20220613140050im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to move an object a fixed distance along one of its axis 1 Answer
Translating measurement in rotation speed and game object size to non-technical staff 0 Answers
Flip over an object (smooth transition) 3 Answers
Rotation& translation problem 0 Answers
Rotation weirdly affects translation 0 Answers