How to make an object shoot a projectile?
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!
Answer by Mrslayer01 · Nov 29, 2015 at 10:20 PM
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.
Answer by Elinoch · Apr 02, 2017 at 09:53 AM
@Mrslayer01 I Tried Using That Script But Whenever I Click The Button The Projectile That Was Already Shot Duplicates
$$anonymous$$ake sure you are not instantiating the instantiated projectile. If you are not, also make sure that you are not shooting the original. Also, this should be a comment, not an answer.
Answer by thuennes · Sep 24, 2017 at 03:28 PM
Doesn't work, the projectile only shoots in one direction, also if i move the GameObject.
The projectile won't shoot in any other direction; the script is to make the bullet duplicate and move. It's up to you to point the bullet in the right direction. Also, don't make this an answer. If you want to reply to his answer, comment on it.
Answer by PRABHBIR123 · Jan 27, 2019 at 03:45 PM
Hey @Jimangel check out this tutorial https://youtu.be/O9MobBiXgno