- Home /
Instantiate with parent/gameObject's velocity
I'd like to drop a projectile and have it share it's parent/gameobject that dropped its velocity. As it stands now, the missile being dropped starts at a velocity of zero (falling quickly behind the player's ship).
There are similar questions to this one on this site, but no answers have worked for me yet : /
var projectile : GameObject;
Instantiate(projectile, transform.position, transform.rotation);
projectile.velocity = GameObject.velocity + speed * transform.forward;
the error i keep getting is:
NullReferenceException: Object reference not set to an instance of an object
I think unity doesn't recognize the phrase "projectile.velocity" but really i have no idea. If some one can tell me how to instantiate a projectile with the velocity of the gameObject which spawned it I'd be very grateful.
I'd settle for preset velocity on an instantiate object, if that's all that can be done..
Answer by GuyTidhar · Jun 04, 2012 at 07:29 AM
try this:
// this is the reference to the projectile prefab, from which you will create such
var projectilePrefab : GameObject;
function CreateProjectile()
{
// Make room in memory for new projectile
var projectile : GameObject;
// Fill the memory with the data from the projectile prefab
projectile = Instantiate(projectilePrefab, transform.position, transform.rotation);
// Set the new projectile with base velocity of 'this' plus speed and direction
projectile.velocity = gameObject.velocity + speed * transform.forward;
}
Too bad this no longer work, there is no longer .velocity under a GameObject. Instantiate also returns an Object and have to be cast to a GameObject.
Answer by Zarkow · Aug 05, 2015 at 06:42 PM
One approach, if you are doing a 2D game:
GameObject bulletRef = Instantiate(bullet, transform.position, Quaternion.identity) as GameObject;
var bulletBody = bulletRef.GetComponent<Rigidbody2D>();
var v = new Vector2(0f, 10.0f);
v = Quaternion.Euler(0, 0, m_Rigidbody2D.rotation) * v;
v += m_Rigidbody2D.velocity;
bulletBody.velocity = v;
This example assumes you want the projectile to have a base-speed of 10.0f, and want it to fly in the direction of the sprite looking up (think 2D space shooter), and that you also want the projectiles to inherit the full velocity of the shooter.
(Example can be condensed, spread it out a bit to make it more readable.)
Your answer
Follow this Question
Related Questions
Help Guitar Hero Style or similar 0 Answers
Velocity and AddForce Problems 0 Answers
Runtime prefab instantiation issue 1 Answer
Checking if object intersects? 1 Answer