Hi everyone!!!
Im having some troubles with shooting.
What I do is making a raycast and at the same time instantiate a particle prefab that looks like a fireball and move that fireball position so it seems like you are actually shooting something.
It doesnt have any collider or rigidbody just the particle system.
The problem is that the raycast kills the enemy immediatly and the ball takes some time to get to the enemy, not much, but you can see the delay.
Also I instantiate a little explosion at the hit.point, but again It appears immediatly and the fireball didnt even get near. And on longer distances its much noticeable.
How can I fix that?
Im gonna show you my code so maybe its easy to guess the problem.
Shooting code
public void Shooting()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 mousePos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y);
Vector2 pos = transform.position;
dir = (mousePos - pos);
Instantiate(explosion, ShootingPoint.position, explosion.transform.rotation);
hit = Physics2D.Raycast(pos, dir.normalized);
if (hit.distance != 0)
{
Debug.Log(hit.distance);
Debug.Log(hit.collider.gameObject.tag);
}
Debug.DrawRay(pos, dir * 1000, Color.red, 5f);
}
}
Particle movement code
void Update ()
{
transform.position += dir.normalized * speed * Time.deltaTime;
Vector3 hit = FindObjectOfType<PlayerControl>().hit.point;
Vector3 dis = hit - transform.position;
if (dis.magnitude <= 1.5f)
{
if (FindObjectOfType<PlayerControl>().hit.collider != null)
{
if (FindObjectOfType<PlayerControl>().hit.collider.gameObject.tag == "Enemy")
{
Destroy(FindObjectOfType<PlayerControl>().hit.collider.gameObject);
}
Destroy(this.gameObject);
}
}
}
Sometimes this works, and sometimes the ball can go through walls instead of destroying itself.
At the point where you are calculating the “dis” variable (I assume that is distance), take a look at what the values of hit and transform.position are each frame.
You can do this by using Debug.Log() (painful) or by debugging and breakpoints (ideal).
Another way to do that is to use GameObject.CreatePrimitive( PrimitiveType.Sphere) to instantiate pairs of “debugging spheres” in your scene ( you might have to scale them down a lot) and that way you can name those “debug objects” with “hit” and “other” or whatever, and then pause the game and see where they are.
That’s the coolest part of Unity3D: doing mid-game shenanigans like this to figure out what is happening!