void Start()
{
rb = GetComponent();
}
void Update()
{
if(Input.GetKeyDown(KeyCode.W))
{
rb.AddForce(Vector3.forward * speed);
}
if(Input.GetKeyUp(KeyCode.W))
{
rb.velocity = Vector3.zero;
}
if(Input.GetKeyDown(KeyCode.S))
{
rb.AddForce(Vector3.back * speed);
}
if(Input.GetKeyUp(KeyCode.S))
{
rb.velocity = Vector3.zero;
}
if(Input.GetKeyDown(KeyCode.A))
{
rb.AddForce(Vector3.left * speed);
}
if(Input.GetKeyUp(KeyCode.A))
{
rb.velocity = Vector3.zero;
}
if(Input.GetKeyDown(KeyCode.D))
{
rb.AddForce(Vector3.right * speed);
}
if(Input.GetKeyUp(KeyCode.D))
{
rb.velocity = Vector3.zero;
}
}
}
Fyi, speed = 10,000
My problem is ;
the character won’t turn.
The character won’t start.
It goes a certain distant even if you hold the button down.
Can someone please help me, I so thank you.
what you’re doing is only applying force wen the key is pushed down not while you’re holding it . try using getkey(keycode. [key you want]) .
also try applying force in the fixed update ,at the moment your speed depends on your framerate which isn’t good for different situations
If you want to add a rotational force to a rigidbody then you need to use the “AddTorque” method. Instead of pushing your object in a given direction, a torque will rotate your rigidbody around an axis.
rb.AddTorque(transform.up * speed * turnDirection);
This line would add a rotation to your rigidbody, similarly to how you currently do with regular forces. It’s using transform.up because (assuming you’re working in 3D space) that’s the axis around which you want to rotate. Then speed is the scale and turnDirection can be a 1 or -1 depending on which way you’re turning.
I won’t write much more on this because I am unsure about how you want to rotate your character - are A and D intended to be rotation?
The only other possibility I think I should cover is if you want your character to just rotate to the way you’re moving. If this is the case then you can just set the rotation to point you forward:
// do this check to ensure we're not rotating towards (0,0,0) - which doesn't make sense!
if (rb.velocity > float.Epsilon)
{
// convert our movement direction to a rotation
Quaternion lookForwardRotation = Quaternion.LookRotation(rb.velocity);
// similar to 'transform.rotation =' but for rigidbodies
rb.MoveRotation(lookForwardRotation);
}