Hi
Iam new to Game Development and tried to create a small 2d platformer.
The movement works perfectly fine in the Editor, but when i build the game, Left and Right movement breaks.
This is the script:
//jump
if (Input.GetKeyDown(KeyCode.W) == true && grounded == true)
{
myRigidbody.AddForce(Vector2.up * jumpheight);
}
//right
if (Input.GetKey(KeyCode.D) == true)
{
myRigidbody.AddForce(Vector2.right * movementspeed);
}
//left
if (Input.GetKey(KeyCode.A) == true)
{
myRigidbody.AddForce(Vector2.left * movementspeed);
}
I have no idea what causes this and any help is appreciated.
Thanks in Advance
1 Like
Please provide a full class and screenshots from the inspector from this object.
Provide a full class to provide qualified support.
What I noticed for now:
Input monitoring and Physics changes must be in Update()
and FixedUpdate()
appropriately. You mixed them up. So you can see a different picture on each device in terms of operating with frame rate.
Class should be the base class of the Object.
I tried using Update() and FixedUpdate() but that didn’t seem to fix it.
Can you maybe share a gif of what happens in editor and in build?
As it seems it does work. Maybe editor goes uncapped on FPS and it seems smoother.
See what I found online:
“By multiplying a movement value by Time. deltaTime, developers can ensure that the object moves at a consistent speed, regardless of the machine’s performance. The Time. deltaTime is calculated by dividing the time since the last frame by the target frame rate, which is typically 60 frames per second (FPS) .”
myRigidbody.AddForce(Vector2.right * movementspeed * Time.deltaTime);
myRigidbody.AddForce(Vector2.left * movementspeed * Time.deltaTime);
I tried this, but it broke left and right movement entirely, both in the build as well as the editor.
Update: I rewrote pretty much all the code (rewrote is a strong word i used a guide), and it for some reason works now.
Thanks to all the people who tried to help me, even though you couldn’t help.
@makaka-org first assessment was correct, honestly, though you seemed to have ignored it.
You were likely polling input in Update, but also applying forces in that same part of the player loop. Due to the different framerates you might get in the editor and build, you will get different results.
Multiplying by Time.deltaTime
is NOT the correct thing to do with physics, as the physics system is already accounting for time. Doing so generally just makes your forces incredibly small, meaning you have to crank up your forces unnecessarily.
As makaka mentioned, you want to poll inputs in Update, but apply physics in FixedUpate.