- Home /
Question by
samaxi · Nov 16, 2013 at 11:40 AM ·
fpsgunsphere raycast
How to shoot RayCast in center of screen?
I need some scripting help
My Code
#pragma strict
var damage : float = 1;
var bulletsinclip = 30;
var bulletsperclip = 30;
var clips = 3;
private var nextFireTime = 0.0;
var fireRate = .02;
function Update () {
if (Input.GetKeyDown (KeyCode.R)){
Reload();
}
if (Mathf.Abs(Input.GetAxis("Vertical")) > 0.1)
animation.CrossFade("Move");
else
animation.CrossFade("Idle");
if (Input.GetKeyDown (KeyCode.G)){
animation.Play("select");
}
if (Input.GetKeyDown (KeyCode.H)){
animation.Play("Put Away");
}
if(Input.GetMouseButton(0)){
if (Time.time - fireRate > nextFireTime)
nextFireTime = Time.time - Time.deltaTime;
while( nextFireTime < Time.time && bulletsinclip != 0) {
FireOneShot();
nextFireTime += fireRate;
}
}
}
function Reload(){
animation.Play("Reload", PlayMode.StopAll);
bulletsinclip = bulletsperclip;
clips --;
}
function FireOneShot(){
animation.Play("Auto");
bulletsinclip -= 1;
var direction = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
var localOffset = GameObject.Find("GunTip").transform.position;
if (Physics.Raycast (localOffset, direction, hit, 300)) {
Debug.DrawLine (localOffset, hit.point, Color.cyan);
// - send damage to object we hit - \\
hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
}
}
function OnGUI () {
GUI.Label (Rect (10, 10, 100, 20), "Ammo: " +bulletsinclip);
GUI.Label (Rect (10, 30, 100, 20), "Bullets Left: " +clips * 30);
}
I understand that the "bullets" (raycast) shoots from the guntip but how do i make it go to the center of the screen?
Comment
Answer by meat5000 · Nov 16, 2013 at 11:41 AM
In screen coords the centre would be screen.height/2 screen.width/2
Use Screen to World function, perhaps.
Read the link on how to use the function. Feed the function into your RayCast. There are many questions on this topic you can draw a solution from :)