- Home /
Shoot projectile straight from player no matter the rotation.
I'm trying to shoot a projectile from the front end of my ship (player) but it always shoots off to the side as soon as I rotate the player. I think it has something to do with the parent/child objects in the player hierarchy but I'm not skilled enough to fix it.
I'll put the prefab hierarchy here:
Player(An empty storing box colliers and movement script)
Camera
Ship model (No scripts or rigidbody attatched)
Particle trails x 2
shootSpawner (The EMPTY OBJ with the script attached)
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class Shoot : MonoBehaviour {
//The thing being shot and the force it is shot at
public GameObject projectile;
public float shootForce;
public Transform shootPos;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void ShootMethod()
{
//Instatntiated from empty and is shot in forward dir.
//PROBLEM WITH OBJ NOT BEING SHOT STRAIGHT AT ALL TIMES, NEEDS FIXING.
//AddFORCE ISNT WORKING REMOVED.
GameObject bullet = Instantiate(projectile, shootPos.transform.position, shootPos.transform.rotation);
bullet.GetComponent<Rigidbody>().AddForce(transform.forward * shootForce);
//Add an IEnumerator for fire rate (public float for wait time)
new WaitForSeconds(5f);
Destroy(bullet, 5f);
}
}
Answer by jokehboy · Mar 04, 2018 at 09:39 PM
It seems it's a case of inertia... the object shoots straight but due to the speed of the ship it passes the point of the instantiation making it look off. I changed my code and it will now shoot 'straight' but still look off.
GameObject bullet = Instantiate(projectile, transform.position, transform.rotation); bullet.GetComponent().AddForce(shootPos.forward * -5000);
I know there's a way to shoot from a ray cast and if a reference could be posted that would be great.
Because once I've got the shooting solved I'm turning the ball into a laser beam.
hmm, did you think about adding your current velocity and deltaRotation to the transform.position / rotation?