Player not moving in the right direction instantly
Okay, so here is the deal.
I've created a script to try and recreate the Infinite Runner. The script should tell the player to move 90 degrees to the left when it is moving forward and 90 degrees to the right when it is moving to the left. That is kinda working but the thing is, which ever input I use, sometimes it just doesn't register correctly. It responds for a millisecond but doesn't go the right way all the way. I tried putting it in FixedUpdate and Update but nothing seems to work. It's a weird question maybe so sorry for that.
I hope someone can help me out here.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour {
public float speed;
private Vector3 dir;
void Start ()
{
dir = Vector3.zero;
}
void Update()
{
if (Input.GetMouseButton(0))
{
if (dir == Vector3.forward)
{
dir = Vector3.left;
}
else
{
dir = Vector3.forward;
}
}
float amountToMove = speed * Time.deltaTime;
transform.Translate(dir * amountToMove);
}
}
Answer by yummy81 · Mar 02, 2018 at 07:03 PM
Look at this line:
if (Input.GetMouseButton(0))
and make it look like that:
if (Input.GetMouseButtonDown(0))
Thank you so much! It worked. I have been looking for a solution for days now,didn't know it would be this easy.
Any chance you could quickly explain to me why my choice of Get$$anonymous$$ouseButton(0) did not work?
Thanks!
So, simply speaking, it works this way. If you press the button and hold it down for a period of time (not releasing it) Get$$anonymous$$ouseButtonDown will be registered only once. Unity assumes that you pressed the button only once despite the fact that it is held down all the time. By contrast, in case of Get$$anonymous$$ouseButton Unity assumes that you keep pressing button all the time and registers it multiple times. Just test it. Put this script on empty gameobject, run, press the button down and hold it down, and look at the console. In the first case you will see that the variable "t" is one, and in the second case "t" is constantly increasing. This is exactly what caused this erratic behaviour in your game:
First code:
public float t;
private void Update()
{
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
t++;
Debug.Log(t);
}
}
and then try this:
public float t;
private void Update()
{
if (Input.Get$$anonymous$$ouseButton(0))
{
t++;
Debug.Log(t);
}
}
Your answer
Follow this Question
Related Questions
How can I make the camera not overreach a limit of rotation one axis. 0 Answers
how to move a gameobject based on a dice roll 1 Answer
OnTriggerEnter2D problem 1 Answer
Script not working for me 2 Answers
Why can I only move upwards? 1 Answer