- Home /
Correctly positioning the start of projectile position
I have the following code;
if (Bullet == null)
Bullet = Instantiate(Resources.Load("PrefabBullet")) as GameObject;
GameObject o = GameObject.FindGameObjectWithTag("Player");
var player = o.transform;
var shootPos = player.position + player.forward * 0.9f;
//Position the bullet to come from the middle of the player
//shootPos.z = shootPos.z - 1.0f;
//shootPos.x = shootPos.x - 0.5f;
var instance = (GameObject)Instantiate(Bullet, shootPos, player.rotation);
Vector3 bulletDirection = new Vector3(target.position.x-transform.position.x,
0.0f,
target.position.z-transform.position.z ) * bulletSpeed;
//Debug Statements
//print(transform.position);
//print(target.position);
//print(bulletDirection);
instance.rigidbody.velocity = bulletDirection;
Now when I trigger the shot button my projectile is drawn on the screen and moves towards my target. What I am struggling to understand is how to make the projectile start from the center of my 'player' model, and then to travel in a horizontal plane towards the target. (I have gravity behaviour off). It seems that no matter how I tweak the shootPos I cannot get it to be consistently at the center of the player, nor to move in a horizontal line. (It moves straight, but sometimes goes up at an angle to the horizontal plane.)
I guess this is either down to some bug in my above code, or more likely down to my understanding of the math involved. So can somoen explain to me what I am doing wrong, or what incorrect assumption I have made?
shadowriffe. That has helped some. However if I am shooting straight ahead, there still appears to be some glitch in the position of the projectile (it leaves the character, and then jumps slightly.)
Whats infuriating is that I have added a collision detection script to the projectile, and that isn't triggering, so I can't stop it and try to see whats happening.
Answer by shadowriffe · May 29, 2012 at 04:10 PM
Just a shot in the dark here, but there may be some weird collisions happening inside your character before the projectile leaves.
http://unity3d.com/support/documentation/ScriptReference/Physics.IgnoreCollision.html
Take a look at that function, and see if keeping the collider of your projectile and the collider of your character from colliding helps.