Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

codingfarm

마우스를 따라다니는 오브젝트 본문

Unity3d

마우스를 따라다니는 오브젝트

scarecrow1992 2022. 10. 3. 17:22

3D

2가지 방법 사용가능

  1. Ray 사용
    • 카메라에서 마우스를 향하는 ray와 plane을 상호작용하여 얻은 좌표에 오브젝트를 위치시킨다
    • 게임이 플레이 되는 floor에 오브젝트 위치 가능
  2. ScreenToWorldPoint 함수 사용
    • 카메라에 투영되는 평면상에 오브젝트 위치
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class MouseChaser : MonoBehaviour
{
    public Transform ob1, ob2;
    Vector3 pos;
 
    // Update is called once per frame
    void FixedUpdate()
    {
        // ob1
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Plane groundPlane = new Plane(Vector3.up, new Vector3(0f, 0f, 0f));
 
        float rayDistance;
 
        if (groundPlane.Raycast(ray, out rayDistance))
            pos = ray.GetPoint(rayDistance);
 
        if (ob1 != null)
            ob1.position = pos;
 
 
        // ob2
        pos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 9f));
 
        if (ob2 != null)
            ob2.position = pos;
 
    }
}
 
cs

 

 

 

 

 

 

 

 

 

'Unity3d' 카테고리의 다른 글

Lerp와 deltaTime 함께 쓰기  (0) 2022.10.05
input event 인터페이스 관련  (0) 2022.09.17
애니메이션  (0) 2022.02.22
네비게이션 메쉬(Navigation Mesh)  (0) 2022.02.22
상속  (0) 2022.02.21
Comments