-->

分類

2016年5月3日 星期二

unity讓物件面對滑鼠方向(make 3D object face to mouse cursor)

有人問了這問題
就放個code


using UnityEngine;
using System.Collections;

public class TraceMouse : MonoBehaviour {
    private Camera mainCamera;
 // Use this for initialization
 void Start () {
        mainCamera = Camera.main;
    }
 
 // Update is called once per frame
 void Update () {
        //transform object to screen space
        Vector3 transformScreenPosition = mainCamera.WorldToScreenPoint(transform.position);
        //use object's z in screen space as mouse's z in screen space, then calculate mouse's world position 
        Vector3 mouseWorldPosition = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transformScreenPosition.z));
        //direction from object to mouse
        Vector3 dir = (mouseWorldPosition - transform.position).normalized;
        //set direction to object's local axis
        transform.up = dir;
    }
}

沒有留言:

張貼留言