Hi all, I came across the answer below and I am trying to get it to work in my game:
I have a touch button you press that then fires a rocket, this is the code i’m using (see below question for code).
I have a gun barrel attached as a child object to my character controller, a target crosshair and a rocket prefab.
The problem I am having is that when I have rigidbody addforce or constant force (tried both out), (added to my rocket prefab to make it move once instantiated) it always fires in the same direction.
Without either of those to make it move, the rocket is instantiated in the direction I am facing correctly (but obviously doesn’t move).
I can’t figure out what is wrong can anyone help please?
private var ray : Ray;
private var rayCastHit : RaycastHit;
var crosshair : GameObject; // game object that goes where the ray collides. make this an empty game object.
var bullet : GameObject;// the projectile being fired.
var pnt : GameObject; // point where bullet is instantiated from. place this object where you want bullet to fire from.
function Update(){
if(Input.GetMouseButtonDown(0)){
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit)){
//add name of object/button to affect in ""
if(rayCastHit.transform.name == "button_2"){
var ray = Camera.main.ScreenPointToRay (Vector3(Screen.width/2,Screen.height/2,0));
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 10000)) {
Debug.DrawLine (ray.origin, hit.point);
crosshair.transform.position = hit.point;
pnt.transform.LookAt(hit.point);
}
Instantiate(bullet,pnt.transform.position,pnt.transform.rotation);
}
}
}
}