- Home /
How can I make my rigidbody character move in the direction my camera is facing? ,
public class marblemovement : MonoBehaviour { public float speed; public float maxSpeed = 10; private Rigidbody rb; public float jumpheight; private float distToGround = 1.5f; public float jumpSpeed = 10f; public float distance = 5f;
void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space)&&isGrounded())
{
rb.AddForce(new Vector3(0, jumpheight, 0));
}
Debug.Log(isGrounded());
if (Input.GetButtonDown("Jump") && isGrounded())
{
rb.AddForce(new Vector3(0, jumpheight, 0));
}
}
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
// Debug.Log(isGrounded());
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
}
bool isGrounded()
{
return Physics.Raycast(transform.position, Vector3.down, distToGround);
}
}
I barely know anything right now and I'm trying to copy and retain some things. I'm also using cinemachine if that helps. Hopefully this makes sense, sorry if it doesn't. ,
Answer by ahsen35813 · Mar 28, 2021 at 10:01 PM
First, apply the camera's y rotation to the player, then use rb.AddRelativeForce
or rb.AddForce(transform.forward * power)
for example. These two solutions both apply force in the forward direction based on the player's local rotation.
Your answer
Follow this Question
Related Questions
Collision with camera inspection target 0 Answers
Jitter on Object with Rigidbody 0 Answers
Camera twitching problem 0 Answers
Orbit cam and Rigidbodies aiming 0 Answers