Hey guys, this is pretty specific, I tried searching but couldn’t find anything that matched my problem exactly. Here’s a link to a youtube video of my game playing and you’ll see that I first shoot a couple of times before moving my player object. The projectiles follow the code which looks like this:
Youtube link: EoE first showing - YouTube (Ignore the music, the screen capture program automatically attaches it and I don’t know how to remove it)
Instantiate Bullet Prefab
LookAt MousePosition
Velocity = tranform.forward * shotSpeed(public variable)
This works out fine. I have a disabled camera that is a child of my player object that I use to do the raycast and a plane that is at 0y while my disabled camera is at 2y. (It’s 2D as the video shows so I’m looking down the y-axis and tranform.forward, the z-axis is my up/down, x-axis is my left/right)
However, as you can see in the video, after I move the player object in any direction, something breaksdown and I’m no longer getting an accurate shot. It seems to be random even and sometimes won’t work if I try to shoot south of the player object.
I’m really not sure what’s happening here, it seems like it must be something small that I’m just not aware of being a problem because it works fine before I move the player transform… Thanks in advance to anyone who answers, and also thanks for even looking at my problem!
This is the script attached to the prefab bullet. It is instantiated when the user clicks the mouse button:
void Start () {
playerCam = GameObject.FindGameObjectWithTag("PlayerCamera").camera;
RaycastHit hit;
Ray ray = playerCam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
gameObject.transform.LookAt(hit.point);
Debug.Log ("hit point " + hit.point);
rigidbody.velocity = transform.forward * shotSpeed;
}
}