How can i make a cannon ball go forward?
Hi, i'm trying to learn to instantiate, and to impulse an object forward. In this case, i got a cannon, that instatiates a cannonball when pressing fire button, and i want to impulse the cannonball forward (just like a cannon ball does), but i'm cant figure out a solution.. I'm a begginer with unity, and i could really use some help.. It's hard to find the logic, but the cannon ball does not instatiate, and it's not push forward. Sorry for the bad english :p
using UnityEngine;
using System.Collections;
public class Disparar : MonoBehaviour {
public GameObject cannonBall;
public Transform spawn;
public float thrust;
public float gravity;
void Start () {
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Rigidbody clone;
clone = Instantiate(cannonBall, new Vector3(spawn.position.x, spawn.position.y, spawn.position.z), Quaternion.Euler(0f, 90f, 0f)) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.forward * thrust);
}
}
}
Answer by pankajb · May 14, 2016 at 03:20 AM
Did you set value to thrust ?? in inspector ?? also make sure you have rigidbody attached to cannonBall Try something like this
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
GameObject clone;
clone = (GameObject)Instantiate(cannonBall, spawn.position, Quaternion.Euler(0f, 90f, 0f));
clone.GetComponent<Rigidbody>().AddForce(transform.forward * thrust);
}
}
or simply replace thrust with value
clone.GetComponent().AddForce(transform.forward * 1000);
there is nice documentation on rigidbody addforce http://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
I am on mobile, so haven't tested. But I think ins$$anonymous$$d of clone angles.. get spawnObject ( Cannon ) angles and try it.
clone.GetComponent<Rigidbody>().AddForce(spawn.forward * thrust);
This works perfectly, thank you :) I was managing the impulse with the rotation of the cannon ball itself, i used the rotation of the spawn just like you said and it was perfect.