拍摄到屏幕中央

时间:2015-04-25 08:32:43

标签: c# unity3d


此代码用于直接激发激光。

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

1 个答案:

答案 0 :(得分:1)

您可以使用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是一个公共浮子,它是您希望激光器行进的速度。您可以根据需要进行更改(对于您提供的代码,laserSpeed将为80)。