Reputation: 19
Here is my code:
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;
public float forwardForce = 4000f;
public float sidewaysForce = 100f;
// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if( Input.GetKey("d") )
{
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if( Input.GetKey("a") )
{
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
}
Please help.
Upvotes: 1
Views: 1841
Reputation: 616
You will want to move your logic to get inputs into the Update()
method. From there, you can set a value for the force then add this force to the RigidBody in FixedUpdate()
. This way, we will be sure the logic for getting input is detected every frame.
private float movement = 0f;
void Update()
{
if( Input.GetKey("d") )
{
movement = sidewaysForce;
}
else if ( Input.GetKey("a") )
{
movement = -sidewaysForce;
}
else
{
movement = 0f;
}
}
void FixedUpdate()
{
rb.AddForce(0, 0, forwardForce * Time.fixedDeltaTime);
rb.AddForce(movement * Time.fixedDeltaTime, 0, 0, ForceMode.VelocityChange);
}
I've also updated Time.deltaTime
to Time.fixedDeltaTime
since you are calling it in FixedUpdate()
.
Finally, you may want to test with different force modes when adding the sideways force.
Upvotes: 1
Reputation: 31
Let's try a few things. First, trying taking out Time.deltaTime in FixedUpdate. When it comes adding forces in FixedUpdate, you normally don't need to useTime.deltaTime.
Secondly, try creating a physics material with zero friction and attaching that to the player object's box collider.
Upvotes: 1