Earlier I asked a question about how to create a projectile and somebody was kind enough to write this script for me:
var theProjectile : UnityEngine.Transform;
function FixedUpdate(){
if(Input.GetKey(KeyCode.Mouse0)){
var bullet = Instantiate(theProjectile, transform.position + Vector3(0, 0, 1), Quaternion.identity);
bullet.rigidbody.AddForce(Vector3.forward * 100, ForceMode.VelocityChange);
}
}
Unfortunately I haven’t been able to get too far with it. I added a long box collider as a child of a capsule collider that has the default 3rd person controller scripts on it. Then I made that box collider a trigger, and added some particles to it, and linked it to the shooting script you see above.
When I start the scene, the shooting works, but only shoots in the direction the box collider was spawned in. I’m trying to figure out how to make the projectile shoot in the direction I am facing when I move around.
Any help is appreciated, as is any references to anything that might help me understand how projectiles and triggers work. If anybody knows about a tutorial that explains shooting I would really appreciate the link.
Vector3.forward gives it the vector3 that the transform your script is on is facing. If it’s on your box collider, it will always shoot in the direction the box is facing.
Nope. Vector3.Forward is a class variable and it is a shorthand writing for Vector3(0, 0, 1); And thus it doesn’t spawn according to your character. Therefore instead of Vector3.Forward, use transform.Forward. It will always refer to your attached transform’s forward.
I was imagining my “projectile” as a laser, so I had a box collider set as a trigger extruded way out in front of my character, expecting the script to “turn it on” and make it active. Once I finally understood rigidbodies, I added one to the box collider (which I wrongly thought was immobile and connected to the player), and then the script worked as it should: it now spawns a physical flying object from the player. (hence the term, projectile)
Once I fixed that, the bullet still didn’t shoot where I was looking. I used transform.forward (no caps) as zine suggested to fix that issue.