- Home /
random direction just in 2d
I have this script to spawn a powered up ball from a brick when hit. What I want it to do is spawn and travel in a random direction. BUT only in the X and Y axis (eg upwards, up-right, right, down-right, down, down-left...etc...) I don't know the wording to add in: instancesuperbullet.rigidbody.AddForce(transform.down * shootforce);
Would it be ...(transform.random, x, y); something like that?
thanks
var prefabsuperbullet:Transform;
var shootforce:float;
function OnCollisionEnter ( collision : Collision) {
if (collision.collider.name == "Bullet"){
var instancesuperbullet = Instantiate(prefabsuperbullet, transform.position, Quaternion. identity);
instancesuperbullet.rigidbody.AddForce(transform.down * shootforce);
}
}
Answer by rutter · May 30, 2012 at 10:15 PM
Not sure exactly what you mean by "only in the X and Y axis", but I'll make an educated guess.
You could try something like this:
var x = Random.Range(-1f, 1f);
var y = Random.Range(-1f, 1f);
var direction = Vector3(x, y, 0f);
//if you need the vector to have a specific length:
direction = direction.normalized * desiredLength;
to clarify, i'm making a breakout game 2d, and i have a brick that when you hit it, it spawns another ball. So I don't want it to spawn on the z axis or it would miss the bricks. Does this make any sense?
Sounds like my guess was more or less on the mark: a vector with randomized X and Y components, but a constant (probably zero) Z component.
Is this the correct way to add the information you gave me into my script? :-
var prefabsuperbullet:Transform; var shootforce:float; var x = Random.Range(-1f, 1f); var y = Random.Range(-1f, 1f); var direction = Vector3(x, y, 0f);
function OnCollisionEnter ( collision : Collision) {
if (collision.collider.name == "Bullet"){ var instancesuperbullet = Instantiate(prefabsuperbullet, transform.position, Quaternion. identity); instancesuperbullet.rigidbody.AddForce(transform.direction Vector3(x, y, 0f) * shootforce); } }
Answer by jtbentley · Jun 05, 2012 at 02:25 AM
var instancesuperbullet = Instantiate(prefabsuperbullet, Vector3( Random.Range(0, 2), Random.Range(0, 2), 0), Quaternion. identity);
@JTBentley hi mate, I tried what you suggested in my script but when I hit my brick with my ball it spawned the superbullet from the centre of the screen in an upwards direction each time. Did I add it incorrectly?
var prefabsuperbullet:Transform; var shootforce:float;
function OnCollisionEnter ( collision : Collision) {
if (collision.collider.name == "Bullet"){
var instancesuperbullet = Instantiate(prefabsuperbullet, Vector3( Random.Range(0, 2), Random.Range(0, 2), 0), Quaternion. identity);
} }
Your answer
Follow this Question
Related Questions
transform.position.x ? 1 Answer
Can't get object to move and rotate on its own axis 2 Answers
How do i lock out a axis 1 Answer
Inverse the mouse position value 2 Answers
Lock a rotation 1 Answer