- Home /
Question by
ThatBroFromFinland · Apr 23, 2015 at 02:37 PM ·
projectiles
Make projectile shoot the direction im looking
Hi guys i have a projectile shooting from my camera.If i look up or straight it shoots straight but if i look down it shoots where it should when i look absolutely straight. Could anyone offer some help? Here is the code:
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
public Rigidbody projectile;
public float fireRate = 1;
private float nextFire = 0.0F;
public float speed = 30;
void Update() {
if (Input.GetButton("Fire1") && Time.time > nextFire) {
nextFire = Time.time + fireRate;
Rigidbody instantiatedProjectile = Instantiate(projectile,transform.position,transform.rotation)as Rigidbody;
instantiatedProjectile.velocity = transform.TransformDirection (new Vector3(0, 0,speed));
}
}
void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
}
}
Comment
Answer by Cherno · Apr 23, 2015 at 03:17 PM
Change this line:
instantiatedProjectile.velocity = transform.TransformDirection (new Vector3(0, 0,speed));
to this:
instantiatedProjectile.velocity = transform.forward * speed;
Hey, thank you for the answer. I tried changing the line to the one you instructed but the problem still occurs.
Answer by ThatBroFromFinland · Apr 23, 2015 at 04:29 PM
FIX! I rewrote some of the code and got this wich works!
using UnityEngine;
using System.Collections;
public class Shoot : MonoBehaviour {
GameObject prefab;
public float fireRate = 1;
private float nextFire = 0.0F;
public float speed = 30;
void Start () {
prefab = Resources.Load ("projectile") as GameObject;
}
void Update() {
if (Input.GetMouseButtonDown(0) && Time.time > nextFire) {
nextFire = Time.time + fireRate;
GameObject projectile = Instantiate(prefab)as GameObject;
projectile.transform.position = transform.position +Camera.main.transform.forward *2;
Rigidbody rb = projectile.GetComponent<Rigidbody>();
rb.velocity= Camera.main.transform.forward * 40;
}
}
void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
}
}
Answer by wdr434-domowe · Mar 29 at 02:04 PM
You can try
GameObject g = Instantiate(prefab, Camera.main.transform.position, Camera.main.transform.rotation);
g.GetComponent<Rigidbody>().AddRelativeForce(Vector3.forward* speed, ForceMode.Impulse);