- Home /
Setting up a basic gun
Ok, I want to set up a character that can attack with a gun. What would be a simple way to shoot with this gun and how would i simply do this via code?
Thanks~
You'll need to be far more specific with your questions and preferably split them into separate questions on this site.
Answer by thendricks · Dec 21, 2012 at 03:05 PM
Here are some scripts I found, it will even let you have multiple guns. Attach player weapons to your characters gun selector(create a game object). Create an empty GameObject. Place it infront of your gun, make it a child of your gun then attach Launcher to your empty object.Assign all of the variables, then you have your gun.
player weapons function Start () { // Select the first weapon SelectWeapon(0); }
function Update () {
// Did the user press fire?
if (Input.GetButton ("Fire1"))
BroadcastMessage("Fire");
if (Input.GetKeyDown("1")) {
SelectWeapon(0);
}
else if (Input.GetKeyDown("2")) {
SelectWeapon(1);
}
}
function SelectWeapon (index : int) {
for (var i=0;i<transform.childCount;i++) {
// Activate the selected weapon
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
// Deactivate all other weapons
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
launcher
var projectile : Rigidbody;
var initialSpeed = 20.0;
var reloadTime = 0.5;
var ammoCount = 20;
private var lastShot = -10.0;
function Fire () {
// Did the time exceed the reload time?
if (Time.time > reloadTime + lastShot && ammoCount > 0) {
// create a new projectile, use the same position and rotation as the Launcher.
var instantiatedProjectile : Rigidbody = Instantiate (projectile, transform.position, transform.rotation);
// Give it an initial forward velocity. The direction is along the z-axis of the missile launcher's transform.
instantiatedProjectile.velocity = transform.TransformDirection(Vector3 (0, 0, initialSpeed));
// Ignore collisions between the missile and the character controller
Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
lastShot = Time.time;
ammoCount--;
}
}
There is an FPS tutorial for free in the asset store if that is what you are trying to create
Your answer
Follow this Question
Related Questions
Shooting Pistol and Machine Gun 2 Answers
reload gun with bullets 2 Answers
Gun and hand animation tutorial! 2 Answers
Raycast gun 2 Answers