其实这个问题,如果直接用collider做完全没什么难度,但是想用射线检测做,纠结了我半天。
直接上代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class atk : MonoBehaviour
{
public BoxCollider2D box; //盒子
public Transform t;//盒子的tansfrom
void Start()
{
}
// Update is called once per frame
void Update()
{
t.right = GetMousePoint();
float a = VectorAngle(transform.right, t.right);
Debug.Log(Physics2D.OverlapBox(transform.position, box.size, a, LayerMask.GetMask("enemy")).name);
}
//计算夹角(有可能是负)
float VectorAngle(Vector2 from, Vector2 to)
{
float angle;
Vector3 cross = Vector3.Cross(from, to);
angle = Vector2.Angle(from, to);
return cross.z > 0 ? -angle : angle;
}
}
子物体挂载盒子,和父物体的right计算夹角,之前测试Z超过180就不准了。这个坑纠结我半天,后来想起来正常使用Z根本不会超过180.
记录下踩过的坑,以及浪费了半天时间的一小段代码。