unity3d 我正在编写一个脚本,使光线投射的方向在统一的2D鼠标

vsikbqxv  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(119)

正如我在标题中所说的,我正在编写一个脚本,使光线投射向鼠标的方向,但由于某种原因,它没有跟随鼠标,而是直接向前。

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        CastRay();
    }

    void CastRay()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
        if (hit.collider != null)
        {
            Debug.Log(hit.collider.gameObject.name);
        }
    }
}
bqf10yzr

bqf10yzr1#

我对这个问题的理解是,您希望在2D中从玩家位置向鼠标位置投射一条光线。如果不是这样,那么您应该编辑您的问题,并给予更多关于您到底想要实现什么的上下文。
如果我理解正确的话,那么答案就是你构建了错误的光线。你所做的是从摄像机的Angular 投射光线,你可以认为这是通过你的显示器向游戏世界投射光线。
若要从玩家角色的Angular 获得光线,光线应该从玩家的位置朝向屏幕空间中的鼠标位置。

// get the player position in screen space
var playerScreenSpacePosition = Camera.main.WorldToScreenPoint(playerPosition);

// calculate ray direction (to - from = direction)
var rayDirection = Input.mousePosition - playerScreenSpacePosition;

// if direction vectors length should be ignored then normalize
rayDirection.Normalize();

// construct the ray with the player being the origin
// (if needed could be Ray2D as well by ignoring 'Z' axis, needs converting position and direction to Vector2)
var ray = new Ray(playerPosition, rayDirection);

// cast for a hit
var hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);

// alternatively: if the length of the raycast shall be defined by the directions magnitude
// (only if direction not normalized, otherwise the rays length will always be one)
hit = Physics2D.Raycast(ray.origin, ray.direction, ray.direction.magnitude);

相关问题