So, I have a cube I can move but I want it to shoot an object from my resources. How do I do it?
using UnityEngine;
using System.Collections;
public class Player_Movement_2 : MonoBehaviour {
public float moveSpeed;
private float maxSpeed = 5f;
private Vector3 input;
void Start () {
}
void Update () {
input = new Vector3 (Input.GetAxis ("Horizontal_2"), 0, Input.GetAxis ("Vertical_2"));
if (GetComponent<Rigidbody>().velocity.magnitude < maxSpeed) {
GetComponent<Rigidbody>().AddForce (input * moveSpeed);
}
if (Input.GetKeyDown(KeyCode.LeftShift)) {
//I want to shoot
}
print (input);
}
}
I just started btw. Thanks in advance!
Well what your want to do is make a object with a rigidbody on it like a cube and make it a prefab. Then you want to add something like this into your code Also be sure to assign the object you made to “projectile”.
public GameObject projectile;
and under Update():
if (Input.GetKeyDown(KeyCode.LeftShift))
{
GameObject bullet = Instantiate(projectile, transform.position, Quaternion.identity) as GameObject;
bullet.GetComponent<Rigidbody>().AddForce(transform.forward * 10);
}
but with this code if the object you are trying to fire will get stuck inside your player. So you would want to have a fire position setup outside of your player and instantiate it there. Just a start but check out the unity resource for rigidbody.addforce Here.
@Mrslayer01 I Tried Using That Script But Whenever I Click The Button The Projectile That Was Already Shot Duplicates
Doesn’t work, the projectile only shoots in one direction, also if i move the GameObject.
Hey @Jimangel check out this tutorial