- Home /
Mouse axes based on position, not movement.
Basically, when I have my cursor in the center of the screen, the camera doesn't rotate. Pretty standard. However, If I move my cursor to the left or right, It will start rotating. Still makes sense. However, When I stop moving the cursor, the rotation continues. I'm using an empty object and making the camera face in the same direction as that empty object. The problem is, the object continues to rotate. If I move the cursor back to the center of the screen, it stops rotating again. Something similar happens when I assign axes in the project settings to the right stick on an Xbox 1 controller. If I move the stick right, the camera begins to rotate, however, if I return the stick to the deadzone, it continues to rotate. If I then move the stick left, it will slow down the rotation, and eventually begin rotating the other direction. It doesn't happen with the vertical stick axis, though. Anyone know what's going on and how to fix it?
Here's my code with the mouse for the player and empty object rotation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public Transform PlayerT;
public Transform camT;
public Transform CamR;
public CharacterController controller;
public float speed;
public float CamRSpeed;
private float gravity;
private float HorizontalR;
private float VerticalR;
private Vector3 moveDirection;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
HorizontalR = Input.GetAxis("Mouse X") * CamRSpeed * Time.deltaTime;
VerticalR = Input.GetAxis("Mouse Y") * CamRSpeed * Time.deltaTime;
CamR.Rotate(VerticalR, HorizontalR, 0f);
PlayerT.forward = CamR.forward;
PlayerT.eulerAngles = new Vector3(0f, PlayerT.eulerAngles.y, 0f);
moveDirection = (PlayerT.forward * Input.GetAxis("Vertical") * speed) + (PlayerT.right * Input.GetAxis("Horizontal") * speed);
controller.Move(moveDirection * Time.deltaTime);
}
}
and for the camera:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraScript : MonoBehaviour
{
public Transform cam;
public Transform player;
public Transform CamR;
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = CamR.position - cam.position;
}
// Update is called once per frame
void Update()
{
cam.eulerAngles = new Vector3(CamR.eulerAngles.x, CamR.eulerAngles.y, 0f);
cam.position = CamR.position - (CamR.rotation * offset);
}
}
Answer by ajwager · Aug 04, 2019 at 04:23 PM
Well, as it turns out, it was simply because the object I was trying to rotate was a child of the player. I'm not entirely sure why it didn't work, but it does now.