Skip to content

Unity3D Notes #11

Open
Open
@dabing1022

Description

@dabing1022
1.Look towards player
using UnityEngine;
using System.Collections;

public class LookTowardMouse : MonoBehaviour {

     void Update () 
     {
         //Mouse Position in the world. It's important to give it some distance from the camera. 
         //If the screen point is calculated right from the exact position of the camera, then it will
         //just return the exact same position as the camera, which is no good.
         Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10f);

         //Angle between mouse and this object
         float angle = AngleBetweenPoints(transform.position, mouseWorldPosition);

         //Ta daa
         transform.rotation =  Quaternion.Euler (new Vector3(0f,0f,angle));
     }

     float AngleBetweenPoints(Vector2 a, Vector2 b) {
         return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
     }  
 }

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions