- Home /
Question by
macalho · Oct 13, 2011 at 05:39 PM ·
instantiatepositionbulletprojectilemouse scroll
Spawn a bullet of a cannon at right position
Hi guys,
I'm still a noob on programming in Unity and I'm trying to make a game with a cannon that can shoot bullets, but right now the bullets are spawned at wrong position: if the cannon is aiming up the bullets are spawned at the bottom of the cannon and if I'm aiming down the bullets are spawned above the cannon. I believe is something with the angle, I guess is inverted, but I still can't figure what is wrong, bellow is my code and thanks in advance for any help!!
//Shoot.js
var bulletPrefab:GameObject;
var temp:GameObject;
var accumulatedForce:int = 0;
var mouseScrollSpeed:float = 5000.0;
var rotationZ:float = 0;
var velX:float = -5.0;
var velY:float = -5.0;
var newX:float = 0;
var newY:float = 0;
function Update ()
{
rotationZ = -Input.GetAxis( "Mouse ScrollWheel" ) *
Time.deltaTime * mouseScrollSpeed;
transform.Rotate( Vector3( 0, 0, rotationZ ) );
newX = transform.position.x + ( Mathf.Cos(transform.rotation.z ) * velX );
newY = transform.position.y + ( Mathf.Sin(transform.rotation.z ) * velY );
if ( Input.GetKey( "mouse 0" ) )
accumulatedForce += 10;
if ( Input.GetKeyUp( "mouse 0" ) )
{
temp = Instantiate( bulletPrefab, Vector3(
newX, newY, transform.position.z ), transform.rotation );
temp.rigidbody.AddForce( -accumulatedForce, accumulatedForce, 0 );
accumulatedForce = 0;
}
}
Comment
Answer by Ludiares.du · Oct 13, 2011 at 05:46 PM
Try creating an Empty in editor mode, make it child of the cannon and then use:
Instantiate(bulletPrefab, spawnpoint.position, spawnpoint.rotation);