피타고라스의 정리
게임에서 피타고라스의 정리는 주로 거리 측정을 위해 활용한다
플레이어 A와 몬스터 B의 거리인 c를 피타고라스의 정리를 통해 알아낼 수 있다
이를 통해
몬스터의 감지 범위 내에 플레이어가 있다면
플레이어를 따라오도록
감지 범위 내에 플레이어가 없다면
움직이지 않도록 구현을 아래의 예시와 같이 구현 가능하다
피타고라스의 정리 예시
먼저 플레이어에 붙일 스크립트인 MoveComponent는 아래와 같이 구현할 수 있다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveComponent : MonoBehaviour
{
public Vector3 dirVec;
public float moveSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float y = Input.GetAxisRaw("Vertical");
//Debug.Log("x: " + x);
// Debug.Log("y: " + y);
dirVec = new Vector3(x, y, 0);
transform.position += dirVec * moveSpeed * Time.deltaTime;
}
}
몬스터에 붙일 스크립트인 FollowComponent는 아래와 같이 구현할 수 있다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowComponent : MonoBehaviour
{
public Transform targetObject;// 타겟 대상 선언
public Vector3 dirVec;
public float moveSpeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(targetObject != null)
{
float x = targetObject.position.x - transform.position.x;
float y = targetObject.position.y - transform.position.y;
double total = System.Math.Pow(x, 2) + System.Math.Pow(y, 2);// Pow는 제곱
double range = System.Math.Sqrt(total);// Sqrt는 루트
// x^2 + y^2의 합에 루트를 씌워 해당 오브젝트와 대상 오브젝트 간의 거리를 구함
if(range > 0.1f && range < 2.0f)
{
dirVec = new Vector3(x, y, 0);
transform.position += dirVec * moveSpeed * Time.deltaTime;
}
}
}
}
그리고 해당 스크립트들에 적절한 MoveSpeed를 입력해 주고
FollowComponent의 TargetObject에 대상을 링크해 주면 된다
그 결과는 아래와 같이 나온다
'게임 수학 & 물리 > 게임 수학' 카테고리의 다른 글
[게임 수학] 벡터의 기초 (2) (0) | 2023.10.17 |
---|---|
[게임 수학] 벡터의 기초 (1) (0) | 2023.10.17 |
[게임 수학] tangent (0) | 2023.10.16 |
[게임 수학] sin, cos (2) (0) | 2023.10.16 |
[게임 수학] sin, cos (1) (0) | 2023.10.16 |