使用 Raycast 的 Unity C# 拍摄脚本

Unity C# Shooting Script with Raycast

我正在 Unity 中创建 2d 头顶游戏。到目前为止,我已经能够让玩家以几乎正确的角度跟随鼠标(但是它仍然以一种奇怪的方式四处移动)。我也在尝试为玩家提供从正确角度(在射击时直接从玩家的顶部)射出射线的射击功能。当我使用此代码单击时,没有任何反应。我为玩家、子弹和火力点设置了对象。

public void Update()
    {


        if (FollowMouse || Input.GetMouseButton(0))
        {
            _target = Camera.ScreenToWorldPoint(Input.mousePosition);
            _target.z = 0;
        }

        var delta = currentSpeed * Time.deltaTime;

        if (ShipAccelerates)
        {
            delta *= Vector3.Distance(transform.position, _target);
        }

        angle = Mathf.Atan2(_target.y, _target.x) * Mathf.Rad2Deg;
        transform.position = Vector3.MoveTowards(transform.position, _target, delta);
        transform.rotation = Quaternion.Euler(0, 0, angle);

        if ((Input.GetMouseButtonDown(0) || Input.GetKeyDown("space")) && Time.time > nextFire && numOfBullets > 0)
        {
            nextFire = Time.time + fireRate;
          //  Instantiate(bullet, firePoint.position, firePoint.rotation);
            numOfBullets--;
            // bullet.transform.position = Vector3.MoveTowards(bullet.transform.position, _target, bulletDelta);
            shoot();
            firePoint.position = _target;
        }

        if(Input.GetMouseButtonDown(1) && fuel > 0)
        {
            currentSpeed = zoomSpeed;
            while(fuel > 0)
            {
                fuel--;
            }
            currentSpeed = ShipSpeed;
        }


    }
    void Start()
    {
        currentSpeed = ShipSpeed;
    }

    void shoot()
    {
        Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
        Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
        RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition-firePointPosition, 100, notToHit);
        Debug.DrawLine(firePointPosition, _target);
    }

试试这个,它会从游戏对象所在的位置发射一条光线,然后朝 transform.right 的方向移动,距离为 100,并忽略 "notToHit"。 debug.drawRay 将在场景视图中显示一条红线,显示光线(距离为 1)。在一切正常后删除它,因为它会减慢你的游戏速度。

RaycastHit2D hit = Physics2D.Raycast(gameObject.transform.position,transform.right,100, notToHit);
if (hit.transform != null) {
    Debug.Log ("You Hit: "hit.transform.gameObject.name);
}
Debug.DrawRay (gameObject.transform.position, transform.right, Color.red, 5);

我使用 transform.right 而不是计算与鼠标位置的角度的原因是因为你说玩家跟随鼠标(所以我假设玩家已经在看鼠标)。但是,如果这不是您想要的,您可以随时将其更改为您想要的方式。