Unity3d
마우스를 따라다니는 오브젝트
scarecrow1992
2022. 10. 3. 17:22
3D
2가지 방법 사용가능
- Ray 사용
- 카메라에서 마우스를 향하는 ray와 plane을 상호작용하여 얻은 좌표에 오브젝트를 위치시킨다
- 게임이 플레이 되는 floor에 오브젝트 위치 가능
- 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 |