Question by
TimidestShadow · May 11, 2020 at 08:19 AM ·
player movement
How can I change this to rotate the player and Not the camera? I was hoping to have the player aim by mouse direction without moving the camera.
public class Player : MonoBehaviour {
CharacterController characterController;
public float speed = 6.0f;
public float jumpSpeed = 8.0f;
public float gravity = 20.0f;
private Vector3 moveDirection = Vector3.zero;
// Start is called before the first frame update
void Start()
{
transform.position = new Vector3(60, 1, 80);
characterController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
//Get the Screen positions of the object
Vector2 positionOnScreen = Camera.main.WorldToViewportPoint(transform.position);
//Get the Screen position of the mouse
Vector2 mouseOnScreen = (Vector2)Camera.main.ScreenToViewportPoint(Input.mousePosition);
//Get the angle between the points
float angle = AngleBetweenTwoPoints(positionOnScreen, mouseOnScreen);
//Ta Daaa
transform.rotation = Quaternion.Euler(new Vector3(0f, angle, 0f));
if (characterController.isGrounded)
{
// We are grounded, so recalculate
// move direction directly from axes
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
moveDirection *= speed;
if (Input.GetButton("Jump"))
{
moveDirection.y = jumpSpeed;
}
}
// Apply gravity. Gravity is multiplied by deltaTime twice (once here, and once below
// when the moveDirection is multiplied by deltaTime). This is because gravity should be applied
// as an acceleration (ms^-2)
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
characterController.Move(moveDirection * Time.deltaTime);
}
float AngleBetweenTwoPoints(Vector3 a, Vector3 b)
{
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
}
Comment
Your answer
Follow this Question
Related Questions
Rigidbody player movement doesn't response to gravity 0 Answers
Door disappearing problem Unity 5.3 3D. 1 Answer
seriously ANIMATOR 0 Answers
Camera spawn rotate with object 0 Answers
How to Apply Animation to Player 0 Answers