- Home /
How to make a player rotate in a direction with a slope of the ground.
Hi, I'm making my first game, but I don't know how to make a player rotate on the same slope as the ground. Sample-(I use rigid body)
I think it can be done with the help of "freeze Rotation", so I got it, but a new problem arose - if I approach the edge of the slope, then the player falls and turns in an unfamiliar direction - either sideways, upside down or backwards . This is not a bad thing until you start moving with the WSAD, because if a player has turned in any other direction, if I press W, then he goes to where the falling has turned-
The code I use-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rigg;
private Vector3 moveDirection;
public float speed;
void Start()
{
rigg = GetComponent<Rigidbody>();
}
void Update()
{
float hor = Input.GetAxisRaw("Horizontal");
float ver = Input.GetAxisRaw("Vertical");
moveDirection = transform.forward * ver + transform.right * hor;
rigg.AddForce(moveDirection.normalized * speed, ForceMode.Acceleration);
}
}
Thanks!
1.
First things first. Make your movement directions relative to camera, not a scene transform:
Transform cameraTransform = Camera.main.transform;
Vector3 cameraRelativeForward = Vector3.ProjectOnPlane( cameraTransform.forward , Vector3.up ).normalized;
Vector3 cameraRelativeRight = Vector3.ProjectOnPlane( cameraTransform.right , Vector3.up ).normalized;
moveDirection = ( cameraRelativeForward * ver + cameraRelativeRight * hor ).normalized;
2.
Box
is not a great shape for a player controller.
3.
Try Sphere
or Capsule
(with frozen XZ rotations) for a controller.
I use a box because the player will need to move other box type objects
Ok. Try new control directions then. This change indirectly should address this orientation issue you mentioned, at least partially.
Your answer
Follow this Question
Related Questions
change direction by rotating object around y axis and adding relative torque 1 Answer
How to have an object inherit rotation of player 1 Answer
Flipping a 2D sprite based on direction along the x axis (2D)? 2 Answers
Rotate object towards target without influencing AddForce 0 Answers
Modify rotation based on passing rigidbody's velocity and direction? 1 Answer