Raycast Shooting Problem

I’m just starting to play with Unity and usually I try to find a solution efore I post, but I hit a brick wall. I have a character that spawns at the beginning of the game. It also spawns a weapon in his hands. The prolem I have is that the spark particles show up on the wall to the left of the character (sic). More than that, the shooting is constant and timers don’t reset if there is a wall to the left, which doesn’t happen if there’s just the floor.

Shooting code for character:

if (inRange == true)
			{
				Move (player.transform);
					if(timer > fireRate && burstTimer > burstRate)
					   {
							gun.Shoot();
							timer = 0;
							burstCount = burstCount + 1;
						}

					if (burstCount == burst)
					{
						burstTimer = 0;
						burstCount = 0;
					}
			}

And code for the gun:

public void Shoot()
	{
		ray.origin = barrelTip.position;
		ray.direction = barrelTip.forward;

		anim.SetTrigger("Fired");
		audio.PlayOneShot(gunShot.clip);



		
		if (Physics.Raycast(ray, out hit, 150))
		{
			GameObject clone = Instantiate(sparks, hit.point, Quaternion.LookRotation(hit.normal)) as GameObject;
			Destroy(clone.gameObject, 0.1f);

			hp = hit.collider.GetComponent <Health>(); 
			hp.TakeDamage (45);
		}
	}

I think that it’s te raycast in the wrong position and/or direction but I can’t see anything wrong in the code. Any help would be appreciated.

Best way is to add some debug code to visualise the ray and check it's what you expect, e.g.: Debug.DrawRay(ray.origin, ray.direction, Color.green, 1, false);

I checked using the Debug.DrawRay and the ray points somewhere to the left, and the position it starts isn't where I want it to either. barrelTip is jus a empty GameObject at the end of the gun, looking at (LookAt) the enemy so i don't know what is actually wrong.

Try adding another empty game object at the back of the gun and then subtracting them, like in my solution. That will give you the line between the two, which will be the direction you want.

Done that, still the same position... Does anyone have any idea where the problem may lie ?

Please post an updated version of your code

1 Answer

1

I may be wrong here as I am new to Unity as well, but I believe your issue is on line 4 of your gun script. barrelTip.forward may not be returning what you are expecting if the local rotation is off. In order to get the direction that the gun is pointed try:

ray.direction = barrelTip.transform.position - barrelBack.transform.position;

This should provide you with a Vector3 that is parallel with your barrel.

Hope this helps!