River Jiang
2020-10-28 d2bc86161bf01b9ac01ba7b4b6ee7e341778c0c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class RotateToMouseScript : MonoBehaviour {
 
    public float maximumLenght;
 
    private Ray rayMouse;
    private Vector3 pos;
    private Vector3 direction;
    private Quaternion rotation;
    private Camera cam;
    private WaitForSeconds updateTime = new WaitForSeconds (0.01f); 
 
    public void StartUpdateRay (){
        StartCoroutine (UpdateRay());
    }
 
    IEnumerator UpdateRay (){
        if (cam != null) {
            RaycastHit hit;
            var mousePos = Input.mousePosition;
            rayMouse = cam.ScreenPointToRay (mousePos);
            if (Physics.Raycast (rayMouse.origin, rayMouse.direction, out hit, maximumLenght)) {
                RotateToMouse (gameObject, hit.point);
            } else {    
                var pos = rayMouse.GetPoint (maximumLenght);
                RotateToMouse (gameObject, pos);
            }
            yield return updateTime;
            StartCoroutine (UpdateRay ());
        } else {
            Debug.Log ("Camera not set");
        }
    }
 
    void RotateToMouse (GameObject obj, Vector3 destination ) {
        direction = destination - obj.transform.position;
        rotation = Quaternion.LookRotation (direction);
        obj.transform.localRotation = Quaternion.Lerp (obj.transform.rotation, rotation, 1);
    }
 
    public void SetCamera (Camera camera){
        cam = camera;
    }
 
    public Vector3 GetDirection () {
        return direction;
    }
 
    public Quaternion GetRotation () {
        return rotation;
    }
}