2015-04-25 133 views
0


拍摄到屏幕中心

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

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

您可以使用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)。

+0

NullReferenceException:未将对象引用设置为对象的实例 LeftGun.Update()(在Assets/Scripts/LeftGun.cs:33)@Edit已解决。使用公共相机myCamera;和var ray = myCamera.ScreenPointToRay(new Vector3(x,y,0));现在它可以工作。谢谢。 – Oen44

+0

@ Oen44你不可以在你的主相机上安装MainCamera标签,这就是为什么...但很好的知道它的工作原理。 – EvilTak