Friday, February 20, 2015

Unity object follow your mouse tutorial

Okay, so let say I am building a spaceship game, and I want the spaceship to follow my finger or mouse whenever i drag the screen, below is how I do it

/////////////////////////////////////////////////////////
public transform mybody;
Vector3 mousePosition;
Vector3 targetPosition;

void FixedUpdate () 
{

        if (Input.GetMouseButton(0)) 
        {
            mousePosition = Camera.main.ScreenToWorldPoint(new Vector3 (Input.mousePosition.x,Input.mousePosition.y,7.59f));


            targetPosition = new Vector3(mousePosition.x,mousePosition.y,mousePosition.z+1.5f);

            mybody.position = Vector3.Lerp(mybody.positiontargetPosition0.1f);
        }

 }

/////////////////////////////////////////////////////////

Drag your spaceship transform to the "mybody"

Lets get down the basic
1. void FixedUpdate () , this function will update every 0.02 seconds

2. if (Input.GetMouseButton(0)) , this mean when the mouse button is click, or finger is pressing down on the iphone

3. Input.mousePosition
=======================
a. Input.mousePosition.X you will get value 0 to 800 (max screen width)
b. Input.mousePosition.Y you will get value 0 to 600 (max screen height)

but, 
a. your spaceship transform.x (value -6 to 6)
b. your spaceship transform.z (value -4 to 4)

4. So you can see both coordinate is not sync, so you need the "Camera.main.ScreenToWorldPoint"
to convert your mouse coordinate to your camera coordinate, and store it inside "mousePosition"

-the "7.59f" is how far your camera from the (0,0,0) point, you can check in unity main camera.transform.position and see the z is how much

5. After you convert the mouse coordinate to your spaceship coordinate, you store them into your "targetPosition", you can see i put +1.5f on z position because i want the spaceship appear higher so that my finger do not block the spaceship 

6. Finally you move your ship slowly from starting position to target position by 0.1f per update by using the Vector3.Lerp function


note:
For simpler code, you can do this

/////////////////////////////////////////////////////////
mybody.position = Camera.main.ScreenToWorldPoint(new Vector3 (Input.mousePosition.x,Input.mousePosition.y,7.59f));
/////////////////////////////////////////////////////////

then your spaceship will teleport to anywhere your finger press

No comments:

Post a Comment