- Home /
My Code isnt 'always' working like it should, but 'sometimes' it does
I have a very simple running 'Game'. In the Game, you have 3 Lanes that you can move to. In my Code i have set the movement to a certain amount of Distance to the left, and right. That means, my Player will always transform to the same Positions. Now, while sometimes my Code works exactly the Way it should, there are cases (f.e. when i play the game on my Laptop, or even on my PC) where the Character moves too much to the left/right and then your Coordinates are ruined and you are moving outside of the Platform.
This is my Code:
public class burgerController : MonoBehaviour
{
// speed is set on 5 in the Editor.
public float speed;
public int counter = 0;
void Update()
{
transform.Translate(Vector3.forward * speed * Time.deltaTime, Space.World);
if (counter >= 0)
{
if (Input.GetKeyDown("a"))
{
transform.Translate(new Vector3(-30, 0, 0) * speed * Time.deltaTime, Space.World);
counter--;
}
}
if (counter <= 0)
{
if (Input.GetKeyDown("d"))
{
transform.Translate(new Vector3(30, 0 , 0) * speed * Time.deltaTime,Space.World);
counter++;
}
}
if (counter == -1)
{
if (Input.GetKeyDown("s"))
{
transform.Translate(new Vector3(30, 0, 0) * speed * Time.deltaTime, Space.World);
counter = 0;
}
}
if (counter == 1)
{
if (Input.GetKeyDown("s"))
{
transform.Translate(new Vector3(-30, 0, 0) * speed * Time.deltaTime, Space.World);
counter = 0;
}
}
}
}
I have used an integer counter, so you cant fall off the Level.
Answer by NoseKills · Jun 14, 2015 at 04:30 PM
In my Code i have set the movement to a certain amount of Distance to the left, and right. That means, my Player will always transform to the same Positions.
That's not what your code is doing :). In all of your Translate calls you have Time.deltaTime as a multiplier. That means the amount you are moving depends heavily on your framerate at the time you press a, s or d.
In your forward movement Translate call you have to use deltaTime, since you do that every frame and you need to move the character a different distance depending on framerate to make the movement smooth.
In your sideways movement code you do the movement instantly and only once when the button is pressed so you should just calculate exactly how much you need to move to left or right and not have any randomness like deltaTime in the parameters.
oh i thought i make the game work independently from the FPS when i put in Time.deltaTime? Could you give me an example how i should change my Code since im just a beginner
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Making a bubble level (not a game but work tool) 1 Answer
How can I get a responsive rigidbody FPS controller without acceleration that reacts to forces? 2 Answers
How to make the enemy stops according the player position 1 Answer