我试图在Unity 2d中创建一个视野。我从旋转的游戏对象投射光线投影,根据角色的外观旋转。但是这个角色来回移动所以当它们向左移动时我将transform.scale设置为-1。问题是,当我这样做时,光线投射不会随角色一起改变方向并保持正确指向!这是代码,我可能遗漏了一些明显的东西!任何帮助将不胜感激!
Transform parent;
float vision_angle_ = 50;
float direction;
Vector3 angle;
Vector2 position;
Quaternion q;
int x = 10;
void Start ()
{
parent = transform.parent;
}
void Update ()
{
direction = parent.GetComponent<Behaviour>().direction;
angle = new Vector2 (x, Mathf.Tan ((vision_angle_) * .5f * Mathf.Deg2Rad) * x);
q = Quaternion.AngleAxis (1, -transform.forward);
position = new Vector2 (transform.position.x, transform.position.y);
for (float i = 0; i < 50; i++) {
angle = q * angle;
RaycastHit2D tile_hit = Physics2D.Raycast (position, transform.TransformDirection (angle), 10);
Debug.DrawRay (position, transform.TransformDirection (angle), Color.green);
}
}
答案 0 :(得分:0)
TransformDirection并未考虑您的转化规模。您可以进行调整以补偿:
Vector2 direction = transform.TransformDirection(angle);
if (transform.localScale.x < 0f) {
direction.x = -direction.x;
}
RaycastHit2D tile_hit = Physics2D.Raycast(position, direction, 10);