繁体   English   中英

如何将光线投射到玩家面对的方向?

[英]How to raycasting to player facing direction?

在我的 2D 自上而下游戏中,我试图从我的玩家向他所面对的方向投射光线。 一切都很好,但问题是玩家停止移动光线投射停止的那一刻(这是有道理的,我正在使用 Input.GetAxis,它在停止移动时返回 0 值)。 我一直在尝试使用 Transform.right / TransformDirection 它只是让光线停留在相同的位置而不是玩家面对的位置。 即使我的播放器停止移动,我有什么方法可以让光线投射继续进行吗?

 public Collider2D GetBarrleCollider() { Physics2D.queriesStartInColliders = false; RaycastHit2D hit = Physics2D.Raycast(this.transform.position, movement, playerDistance); if (hit.collider != null && hit.collider.gameObject.CompareTag("Pickup")) { Debug.Log("Return NOT null" + " " + hit.collider.tag); return hit.collider; } else { Debug.Log("Return null"); return null; } }

 public void MovementHandler() { movement.x = Input.GetAxisRaw("Horizontal"); movement.y = Input.GetAxisRaw("Vertical"); rb2D.MovePosition(rb2D.position + movement * getPlayerMovementSpeed * Time.deltaTime); }

您会将方向存储为变量。 让我们称之为lookDir 然后你应该检查运动向量是否不为零:

Vector2 lookDir;

public void MovementHandler()
{
    movement.x = Input.GetAxisRaw("Horizontal");
    movement.y = Input.GetAxisRaw("Vertical");
    rb2D.MovePosition(rb2D.position + movement * getPlayerMovementSpeed * Time.deltaTime);

    if (movement != Vector2.zero)
    {
        lookDir = movement;
    }
}

然后你可以从这个向量进行光线投射。 这样,您只有在玩家移动时才更改它。

这样的事情应该工作:

public void MovementHandler()
{
    movement.x = Input.GetAxisRaw("Horizontal");
    movement.y = Input.GetAxisRaw("Vertical");
    rb2D.MovePosition(rb2D.position + movement * getPlayerMovementSpeed * Time.deltaTime);

    if (movement != Vector2.zero)
    {
        lookDir = movement;
    }
}
public Collider2D GetBarrleCollider()
{
    Physics2D.queriesStartInColliders = false;

    //this line was changed \/
    RaycastHit2D hit = Physics2D.Raycast(this.transform.position, lookDir, playerDistance);
    //

    if (hit.collider != null && hit.collider.gameObject.CompareTag("Pickup"))
    {
        Debug.Log("Return NOT null" + " " + hit.collider.tag);
        return hit.collider;
    }
    else
    {
        Debug.Log("Return null");
        return null;
    }
}

如果这不起作用,请在评论中告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM