2015-04-25 132 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