- Home /
Camera rotation C# script problem
Can anyone tell me plz, why is this C# script not working. Different glitches, and camera rotates always different directions, and really laggy. I need to fix this entire script.
using UnityEngine; using System.Collections;
public class Cam1 : MonoBehaviour
{
public Transform cam;
public float sp;
public Vector3 mouseDelta = Vector3.zero;
private Vector3 lastMousePosition = Vector3.zero;
void Update()
{
mouseDelta = Input.mousePosition - lastMousePosition;
lastMousePosition = Input.mousePosition;
float x = mouseDelta.x;
float y = mouseDelta.y;
if (y < 0)
{
cam.Rotate(x, 0, 0);
}
if (y > 0)
{
cam.Rotate(-x, 0, 0);
}
if (x > 0)
{
cam.Rotate(0, y, 0);
}
if (x < 0)
{
cam.Rotate(0, -y, 0);
}
}
}
Answer by Gunorgunorg · Jul 03, 2014 at 07:30 PM
You need to make a transform for the mouse position to be the target, and one line will make it look:
transform.LookAt(target);
It took a while for me to figure this out so that the camera stayed still and looked at my player.
Answer by Xyexs · Jul 03, 2014 at 07:34 PM
using UnityEngine;
using System.Collections;
public class CameraScript : MonoBehaviour {
public float mouseSensitivityRightLeft = 5f;
public float mouseSensitivityUpDown = 5f;
float verticalRotation = 0;
float verticalVelocity=0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Rotation
//right/left
float rotLeftRight = Input.GetAxis ("Mouse X") * mouseSensitivityRightLeft;
transform.Rotate(0,rotLeftRight,0);
//up/down
float rotUpDown = Input.GetAxis ("Mouse Y") * mouseSensitivityUpDown;
transform.Rotate(-rotUpDown,0,0);
}
}
I used this just a few minutes ago. It works fine.
Answer by arky25 · Jul 03, 2014 at 07:54 PM
Instead of using Input.mousePosition, use Input.GetAxis("Mouse X") and Input.GetAxis("Mouse Y"), so something like this:
public class Cam1 : MonoBehaviour
{
public Transform cam;
public float sp;
public float speedX;
public float speedY;
void Update()
{
float x = Input.GetAxis("Mouse X") * Time.deltaTime * speedX;
float y = Input.GetAxis("Mouse Y") * Time.deltaTime * speedY;
if (y < 0)
{
cam.Rotate(x, 0, 0);
}
if (y > 0)
{
cam.Rotate(-x, 0, 0);
}
if (x > 0)
{
cam.Rotate(0, y, 0);
}
if (x < 0)
{
cam.Rotate(0, -y, 0);
}
}
}
Your answer
Follow this Question
Related Questions
Flip over an object (smooth transition) 3 Answers
C# GameObject Reverses Z Rotation 0 Answers
C# Rotate GameObjects Regardless of List Size 2 Answers
C# Need Help Refining Ricochet Script 1 Answer
Player lives script help 1 Answer