- Home /
Add relative force to character on input
Hi everyone, i want to make a script for player movment in which the forward direction is relative to the direction the character is facing, the old classic tank controls. I started using transform.Translate and transform.Rotate, but then emerges the problem with slopes: in order to make my character climb up on a slope i had to freeze x and z position, but this obviously doesn't allow collisions with object; so i tried to use RigidBody.addRelativeForce, here's the script (there is also a part used for climbing slopes smoothly).
public class TankControls : MonoBehaviour
{
public Rigidbody thePlayer;
public bool isMoving;
public float horizontalMove;
public float groundCheckDistance = 0.25f;
private void Start()
{
thePlayer = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
if (Input.GetButton("Vertical"))
{
thePlayer.AddRelativeForce(Vector3.forward * 10);
}
if (Input.GetButton("Horizontal"))
{
isMoving = true;
horizontalMove = Input.GetAxis("Horizontal") * Time.deltaTime * 150;
thePlayer.transform.Rotate(0, horizontalMove, 0);
}
Vector3 origin = thePlayer.transform.position - new Vector3(0f, 0.9f, 0f);
RaycastHit hit;
if (Physics.Raycast(origin, -Vector3.up, out hit, groundCheckDistance, ~(gameObject.layer)))
{
thePlayer.transform.Translate(new Vector3(0f, -hit.distance, 0f));
}
}
}
This script doesn't work, i can rotate the player but it can't move, what am i missing?
Your answer
Follow this Question
Related Questions
how do i put a max to rigidbody.AddRelativeTorque 1 Answer
AddForce and AddRelativeForce not forcing in the right directions 2 Answers
3rd Person Controller How to make the player face camera lookdirection [C#] 0 Answers
3rd person game player movement 1 Answer
Pull the player to an raycast.hit 0 Answers