c# - Shooting to the center of the screen -



this code used fire laser straight forward.

using unityengine; using system.collections;  public class leftgun : monobehaviour {  public rigidbody laser; public audioclip lasershot;  float shotspeed = 0.1f; bool canshoot = true;  // update 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) rigidbody;             clone.velocity = transform.transformdirection(-80, 0, 0);             destroy(clone.gameobject, 3);         }     } } 


i fire center of screen (where crosshair is). how can achive that?
example image: http://i.imgur.com/esvsqnd.png

you can use camera.screenpointtoray. ray center of main camera, use:

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 float speed want laser travel at. can change according needs (for code provided, laserspeed 80).


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -