射击到屏幕中央

Shooting to the center of the screen


此代码用于直接向前发射激光。

using UnityEngine;
using System.Collections;

public class LeftGun : MonoBehaviour {

public Rigidbody laser;
public AudioClip LaserShot;

float shotSpeed = 0.1f;
bool canShoot = true;

// Update is called once per frame
void Update () {

    if(!Engine.escape)
    {
        shotSpeed -= Time.deltaTime;

        if(shotSpeed <= 0f)
            canShoot = true;

        if(Input.GetButton("Fire1") && canShoot)
        {
            shotSpeed = 0.1f;
            canShoot = false;
            PlayerGUI.ammunition--;
            audio.PlayOneShot(LaserShot);
            Rigidbody clone = Instantiate(laser,transform.position, transform.rotation) as Rigidbody;
            clone.velocity = transform.TransformDirection(-80, 0, 0);
            Destroy(clone.gameObject, 3);
        }
    }
}


我想向屏幕中央开火(十字准线所在的位置)。我怎样才能做到这一点?
示例图像:http://i.imgur.com/EsVsQNd.png

您可以使用 Camera.ScreenPointToRay。要从主相机的中心获取光线,请使用:

float x = Screen.width / 2f;
float y = Screen.height / 2f;

var ray = Camera.main.ScreenPointToRay(new Vector3(x, y, 0));
clone.velocity = ray.direction * laserSpeed;

laserSpeed 是一个 public 浮点数,它是您希望激光行进的速度。您可以根据需要更改它(对于您提供的代码,laserSpeed 将为 80)。