How to adjust the gun so it always shoots where the aim is

Asked

Viewed 827 times

3

I have a gun that is positioned on the screen manually and I need to create a script in such a way that when I fire, the bullet will reach the point where the sight is aiming, which in this case is the half-screen coordinate.

I also wanted to know how to position the gun (via script) so that the barrel is aligned with the sight.Imagem ilustrativa do desejado

  • Do you shoot how? Do you create the bullet from the gun or from the character? If you use a raycast, do you make it from the gun or the character? It is important to make sure that the direction vector that the bullet follows is normal relative to the camera and that it is the same as the alignment of the barrel of the gun.

  • She doesn’t shoot yet. I thought of instantiating the bullet from the gun so that it would come out the barrel, as it actually happens. I thought that if the script just aligned the barrel of the gun so that it would focus on the scope, by instantiating the bullet it would just follow the direction vector of the barrel. Would that work? The bullet would hit the center point of the screen no matter how far away the target is?

  • 1

    Michael, usually not worth instantiating an object to be the bullet, it consumes game resources and it will move so fast that the player will barely see it. So the recommended is to use a raycast, which basically traces an invisible line and checks if it collides with the other objects of the scenario.

  • @It’s because I thought of making a similar projectile trace we see in FPS games, like the smoke of a bazooka projectile, for example.

1 answer

2

I haven’t touched Unity3d in a while, but I think you can do it using the function Physics.Raycast.

The solution would be to make the weapon always aim for the point that lies right in front of the shooter before you fire the projectile:

 RaycastHit hit;
 bool bloqueado = Physics.Raycast(transform.position, transform.forward, out hit);
 arma.transform.LookAt(bloqueado ? hit.point : transform.forward);

After that, you create the projectile, using the same Quaternion rotation of the weapon and position it right on the tip of it.

  • "Lookat" would not be better enjoyed?

  • @Matheus In fact, I said it’s been a long time since I touched it. ;D - Edited reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.