I am not sure what the proper question is for my problem, so would like to explain how my character is moving with different code, and when I unattach rigidbody, and hope you can help me figure it out.
Here is my case:
I have walls that will stop the player as it colides with the wall, and of course I have rigidbody and character controller attached to the player.
When I run the game using this code below, the player moves and collides with the walls, but it moves too fast, and when I press a key continuously the player goes past the wall and is floating in space.
// If user press W on the keyboard
if (Input.GetKey(KeyCode.W))
{
// Move the player forward
transform.position -= Vector3.forward * moveSpeed * Time.deltaTime;
}
// But if user press A on the keyboard
else if (Input.GetKey(KeyCode.A))
{
// Move the player to the right
transform.position += Vector3.right * moveSpeed * Time.deltaTime;
}
// But if user press S on the keyboard
else if (Input.GetKey(KeyCode.S))
{
// Move the player backward
transform.position += Vector3.forward * moveSpeed * Time.deltaTime;
}
// But if user press D on the keyboard
else if (Input.GetKey(KeyCode.D))
{
// Move the player to the left
transform.position -= Vector3.right * moveSpeed * Time.deltaTime;
}
When I change the code to the below code (Let the Physic Engine do the work) the player does not move through the wall anymore when the key is pressed continuously, but the rotation of the player become weird (e.g: The player is in standing position, but when I press W, A, S or D, the rotation of the player is not standing position anymore.)
int xVelocity = 0, zVelocity = 0;
if (Input.GetKey(KeyCode.W))
{
xVelocity -= 5;
}
else if (Input.GetKey(KeyCode.A))
{
zVelocity -= 5;
}
else if (Input.GetKey(KeyCode.S))
{
xVelocity += 5;
}
else if (Input.GetKey(KeyCode.D))
{
zVelocity += 5;
}
rigidbody.velocity = new Vector3(xVelocity, 0, zVelocity);
When I unattached the rigidbody from the player and move back to the first code, the player does not move weirdly, but it does not check for the collision when the player collides with the walls.
Can someone help me with this?