본문 바로가기

Unity/수업내용

2020-05-22 마우스 클릭받아 이동

Test.class

더보기
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
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
 
public class Test : MonoBehaviour
{
    public GameObject flagGo;
 
    public float speed = 2;
    RaycastHit hit = default;
    private void Awake()
    {
        
    }
    private void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            Debug.LogFormat("down! {0}", Input.mousePosition); // x y z screen (pixel)
 
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Debug.DrawRay(ray.origin, ray.direction * 1000f, Color.blue , 1f);
 
            
            if (Physics.Raycast(ray, out hit, 1000)) { 
                Debug.LogFormat("hit: {0}", hit.point);
 
                //this.flagGo.transform.position = hit.point;
            }
        }
        var moveDir = Vector3.Normalize(hit.point - this.flagGo.transform.position);
        var distance = Vector3.Distance(this.flagGo.transform.position, hit.point);
        var displacement = moveDir * this.speed * Time.deltaTime;
 
        if (distance >= 0.2f)
        {
            this.flagGo.transform.Translate(displacement);
 
        }
 
    }
}