Ok so, I am trying to keep an object moving forward, but when the player clicks the object will move on the x axis +2 or -2 yet remain moving forward. So basically, no matter what the player object is moving forward, then when you click the player will move on the x position either +2 or -2 depending on the last click. So if the last click the player moved +2, the next they move -2. I tried with an if/else, and I really cant figure it out. Please help. Thanks
This is my code: It continuously moves left or right and wont return back to forward
public float speed;
private Vector3 dir;
// Use this for initialization
void Start () {
dir = Vector3.zero;
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
if (dir == Vector3.right)
{
dir = Vector3.left;
}
else
{
dir = Vector3.right;
}
}
float amountToMove = speed * Time.deltaTime;
transform.Translate(dir * amountToMove);
}
Make sure to use code tags:
public float speed;
private Vector3 dir;
private float offset;
// Use this for initialization
void Start () {
dir = Vector3.forward;
offset = 1;
}
// Update is called once per frame
void Update () {
Vector3 moveDir = dir;
if (Input.GetMouseButtonDown(0))
{
moveDir += offset*Vector3.right*2;// *2 to make it to +2/-2
offset = -offset;
}
moveDir *= speed * Time.deltaTime;
transform.position +=moveDir;
}
Now this code lerps the movement to +2/-2 if you want them to instantly telport change it to this:
public float speed;
private Vector3 dir;
private float offset;
// Use this for initialization
void Start () {
dir = Vector3.forward;
offset = 1;
}
// Update is called once per frame
void Update () {
Vector3 moveDir = dir;
Vector3 xDir = Vector3.zero;
if (Input.GetMouseButtonDown(0))
{
xDir = offset*Vector3.right*2;// *2 to make it to +2/-2
offset = -offset;
}
moveDir *= speed * Time.deltaTime;
moveDir += xDir;
transform.position +=moveDir;
}
Thank you so much, it works. Really appreciate it