- Изменено
Spawn bullet at gun barrel
Hi and greetings from Sweden!
I'm trying to shoot bullets from a weapon but can't get it right. The weapon is controlled by the keyboard.
My thought is to have a "barrel bone" for every gun attachment which is the bullet's spawn point, but I don't know how to do this properly.
My code so far:
public void Setup(SkeletonAnimation skeletonAnimation) {
this.skeletonAnimation = skeletonAnimation;
thompsonBarrel = this.skeletonAnimation.skeleton.FindBone("thompsonBarrel");
}
public void Shoot(bool isFacingRight) {
float speed = 1000.0F;
float x = thompsonBarrel.worldX;
float y = thompsonBarrel.worldY;
float rotation = thompsonBarrel.worldRotation;
bullet = (GameObject)Instantiate(bulletPrefab, new Vector3(x, y, 0), Quaternion.Euler(rotation, 0, 0));
//Add force
}
What should be in the Instantiate and add force?
Best regards,
joelwe
transform.TransformPoint(new Vector3(x,y,0), Quaternion.Euler(0,0,rotation))
You'll also need to deal with WorldFlipX and Y.
My suggestion is to simply create a chlid object and attach the BoneFollower script to it and tell it to follow the muzzle bone or use SkeletonUtility.
Hi Mitch, and thank you for your quick reply!
The BoneFollower-script helped me to get the transform.rotation and transform.position, so now the bullet spawns at the barrel which is great! Now I'm trying to add some force to the bullet, but all it does is falling down from the spawning point. What am I missing?
public void Shoot(Vector3 position, Vector3 rotation, bool isFacingRight) {
float speed = 9000.0F;
bullet = (GameObject)Instantiate(bulletPrefab, position, Quaternion.Euler(rotation.x, rotation.y, rotation.z));
bullet.GetComponent<Rigidbody2D>().AddForce(transform.forward * speed);
}
Best regards,
joelwe
- Изменено
Transform.forward means the Z direction.
This would look hilarious if you had a perspective camera.
Oh, you were adding it to the RigidBody2D. So it would just ignore the z component of the vector.
It wouldn't look that hilarious then. :mmm:
yeah, who makes a 3d game with 2d assets......
:think: :x
Plenty of people do.
cool.
Oh man, I must've googled for 3d spawning :p It works now, thank you so much!
public void Shoot(Vector3 position, Vector3 rotation, bool isFacingRight) {
float speed = 9000.0F;
if (isFacingRight) {
bullet = (GameObject)Instantiate(bulletPrefab, position, Quaternion.Euler(rotation.x, rotation.y, rotation.z));
bullet.GetComponent<Rigidbody2D>().AddForce(bullet.transform.right * speed);
}else{
bullet = (GameObject)Instantiate(bulletPrefab, position, Quaternion.Euler(rotation.x, rotation.y, -rotation.z));
bullet.GetComponent<Rigidbody2D>().AddForce(-bullet.transform.right * speed);
}
}