Raycast的Unity C#射击脚本

时间:2019-02-09 19:12:05

标签: c# unity3d 2d-games raytracing

我正在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);
    }

1 个答案:

答案 0 :(得分:0)

尝试此操作,它将从游戏对象所在的位置开始发出光线,并朝着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而不是计算与鼠标位置的夹角的原因是因为您说玩家跟随鼠标(所以我认为玩家已经在看着鼠标了)。但是,如果这不是您想要的,则可以随时将其更改为所需的方式。