- Home /
fire to camera
Hi a have a cube witch is moving left to right into fixed space. I have a raycast to detect when the cube is in front of my cube and in that point, I need the cube to fire a bullet (prefab sphere) to my main camera.
The raycast part is working but I´m no able to fire the bullet to the camera, it alwyas goes parallel to floor, not a line to my camera (it shloud be a diagonal or whatever).
This is my cube.cs
myTransform.position = Vector3.MoveTowards (transform.position, dest, Time.deltaTime * velocidad);
RaycastHit hit;
Vector3 fin = new Vector3(this.transform.position.x,3.5f,9f);
Debug.DrawLine(this.transform.position, fin, Color.red);
if ( Physics.Raycast( this.transform.position, fin, out hit ) )
{
if ( hit.collider.tag == "MainCamera" )
{
if (isShooting == false)
{
isShooting=true;
GameObject BalaEnemigo = (GameObject)GameObject.Instantiate (PrefBalaEnemigo);
BalaEnemigo.transform.position = GameObject.Find("Cubo").transform.position;
BalaEnemigo.transform.LookAt(Camera.main.camera.transform.position);
BalaEnemigo.rigidbody.AddForce (transform.forward *10);
}
}
}
And this is my bullet prefab:
void Start () {
this.transform.position = GameObject.Find ("Cubo").transform.position;
this.transform.LookAt(Camera.main.camera.transform.position);
//Debug.DrawLine(transform.position, transform.position+Vector3.forward*5, Color.blue);
this.rigidbody.AddForce (Camera.main.camera.transform.position *10);
}
I tried a lot of different approaches without any luck. How should a fire from my cube to my camera?
thanks in advance
Answer by Cherno · Mar 09, 2015 at 02:32 PM
In your main script, why are you adding force to the bullet if the bullet already has a script that adds force in Start()? Same goes for the LookAt function.
It would be better to instantiate the bullet, then set it's position (or even better, directly set the right position as part of the Instantiate function, look it up on the Unity API to see what kind of Arguments the Instantiate function accepts), and then call a function on the bullet's script instead of Adding force in the main script or in the bullet's Start().
if (isShooting == false)
{
isShooting=true;
GameObject BalaEnemigo = Instantiate (PrefBalaEnemigo, GameObject.Find("Cubo").transform.position, Quaternion.Identity);
BalaEnemigo.transform.LookAt(Camera.main.camera.transform.position);
BalaEnemigo.GetComponent<BulletScript>().StartMoving();
}
and on your bullet Script:
public void StartMoving() {
rigidbody.AddForce (transform.forward * 10f);
}
Your answer
Follow this Question
Related Questions
raycast hit add force problem, help needed please 1 Answer
different beetween transform.translat and rigidbody.addforce? 1 Answer
How to make a ball stay in the air longer when force is added? 1 Answer
How to aim a ball with cross hair? 2 Answers
Seeking help or Tutorials for Raycast/movement script. 1 Answer