I came across some simple camera control code on Unity Answers and wanted to have a go and expand upon it.
To begin with, i wanted to rotate the camera around a point and be able to zoom in and out.
The easiest way that i have figured out to rotate an object around a point, is to have the object you want to rotate inside another gameobject and rotate that gameobject.
To start with:
private var to : Quaternion;
private var ToX:float;
private var ToY:float;
public var TheCamera:GameObject;
function Start ()
{
to = Quaternion.Euler(0,0,0);
ToX = 0;
ToY = 0;
}
function Update ()
{
//this turns a vector3 into a Quaternion.
to = Quaternion.Euler(ToY,ToX,0);
//this uses the Quaternion and lerps its current position to it.
transform.rotation = Quaternion.Lerp(transform.rotation, to, Time.time * 0.05);
}
From Unity Answers, i found out how to trace if the mouse had moved. But only when the left mouse button was pressed.
if(Input.GetAxis("Mouse X")<-0)
{
ToX -= 2;
}
if(Input.GetAxis("Mouse X")>0)
{
ToX += 2;
}
if(Input.GetAxis("Mouse Y")<-0)
{
ToY += 1;
}
if(Input.GetAxis("Mouse Y")>0)
{
ToY -= 1;
}
This changes what rotation X and rotation Y the camera needs to lerp to.
Tracing the mouse wheel is the same as tracing X and Y movement, but i wanted to limit how far the camera could zoom in and out.
if(Input.GetAxis("Mouse ScrollWheel")<0)
{
if(TheCamera.camera.fieldOfView < 100)
{
TheCamera.camera.fieldOfView += 4;
}
}
if(Input.GetAxis("Mouse ScrollWheel")>0)
{
if(TheCamera.camera.fieldOfView > 10)
{
TheCamera.camera.fieldOfView -= 4;
}
}
I then placed this all inside a if(Input.GetMouseButton(1)) so it was only being traced when the left button was being pressed.
Lastly i looked up a way of locking the cursor to the screen and hiding it. This stops you from accidentally clicking outside of the screen. It is as simple as:
Screen.showCursor = true/false;
Screen.lockCursor = true/false;
Next i placed one of my models in the center to test the code out. Initially i used a lerp to animate the ship hovering, but it was too sharp on the start points. So i wrote a little code that works like a pendulum:
private var MoveUp : float = 0.001;
function Update ()
{
transform.position += Vector3(0,MoveUp,0);
if(transform.position.y < -0.002)
{
if(MoveUp < 0.001)
{
MoveUp += 0.000005;
}
}else if(transform.position.y > 0.002){
if(MoveUp > -0.001)
{
MoveUp -= 0.000005;
}
}
}
End Result:
Camera Test
No comments:
Post a Comment