- Home /
Basic Movement Problems
I'm trying to make a cube move side to side, and I already have the forward movement which works fine. When I hit play, the cube goes forward, but it only manages to go side to side 3/10 times. My code is below. I am taking a course by brackeys to get started with unity. If any of you could help me, that would be welcome.
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public Rigidbody rb;
public float forwardForce = 2000f;
public float sidewaysForce = 500f;
// Start is called before the first frame update
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if ( Input.GetKey(KeyCode.D) )
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey(KeyCode.A))
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange );
}
}
}
Best practice is to put user input functions inside Update, not in FixedUpdate. Otherwise you will lose key presses (learn here the difference https://learn.unity.com/tutorial/update-and-fixedupdate#5c8a4242edbc2a001f47cd63). However since you are using Physics to move the object you want to keep that part in the FixedUpdate.
So check the Input in Update and set class level bool value (for example isDPressed) according to the key presses. Then in the FixedUpdate check that bool value and call the AddForce and then reset the bool value.
Answer by jmhoubre · Nov 30, 2021 at 07:12 PM
Good evening,
I don't quite understand your wish to move the cube "side to side".
The code seems correct to me. Perhaps you are referring to the difficulty? Try to change "ForceMode.VelocityChange" to "ForceMode.Force".
This parameter allows the object to be continuously accelerated taking into account its mass, while VelocityChange abruptly changes the speed without taking into account the mass.
See the documentation at https://docs.unity3d.com/ScriptReference/ForceMode.html