same script, different results every test run
Hi, I was trying to create a character controller and I had a problem where when I try to walk it'd neither go sonic speed or just not move at all. Yesterday I couldn't even get it to move but this morning it moves way too fast. Here's the code (don't mind the jumping part it's bad and ill fix it later): using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Controller : MonoBehaviour
{
private Rigidbody rigidbody;
public float walkSpeed;
public float jumpPower;
void Awake()
{
rigidbody = gameObject.GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
float walkMovement = 0;
float strafeMovement = 0;
if (Input.GetKey(KeyCode.W))
{
walkMovement = walkSpeed;
}
if (Input.GetKey(KeyCode.S))
{
walkMovement = -walkSpeed;
}
// --------------------------------------------------------------------
if (Input.GetKey(KeyCode.A))
{
strafeMovement = walkSpeed;
}
if (Input.GetKey(KeyCode.D))
{
strafeMovement = -walkSpeed;
}
// --------------------------------------------------------------------
if (Input.GetKeyDown(KeyCode.Space))
{
rigidbody.AddForce(0, jumpPower, 0);
}
// Move character
rigidbody.AddRelativeForce(Vector3.forward * walkMovement);
rigidbody.AddRelativeForce(Vector3.left * strafeMovement);
}
}
Answer by DenisIsDenis · Jul 10, 2021 at 02:43 AM
Replace Update()
with FixedUpdate()
. Your problem is related to the frames per second. But the more fps, the more often the force is applied and the higher the speed of the character. FixedUpdate()
is called regardless of fps. Therefore, any device will always have the same speed.
Note: in your script, the player can speed up infinitely. To prevent this, enter the variable
public float maxSpeed = 10;
and write the following code at the end of the FixedUpdate()
function:
var velocity = rigidbody.velocity;
velocity.y = 0;
velocity = Vector3.ClampMagnitude (velocity, maxSpeed);
velocity.y = rigidbody.velocity.y;
rigidbody.velocity = velocity;
Doesn't quite work, It seems to me that it's a problem related to materials, as even when I use FixedUpdate, the controller sometimes doesn't move, but when I move when jumping, it moves perfectly fine. Apologies for not clearing that part up
Yes, physical materials can affect movement on the ground. But in this case, it is advisable to use FixedUpdate()
. Try to write ForceMode.VelocityChange
as the second argument in the AddRelativeForce()
functions. Just keep in $$anonymous$$d that the acceleration will increase greatly, so after that reduce walkMovement
and strafeMovement
.
Your answer
Follow this Question
Related Questions
Gravity is not working 0 Answers
revolving a rigidbody around another MOVING rigidbody 0 Answers
Accelerate Player with Rigidbody.AddForce 0 Answers
Player getting stuck on collider/walls 0 Answers
Character Controller vs Rigidbody 3rd Person Zelda-esque 0 Answers