Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Firing Angle towards Mouse Coordinates

Discussion in 'Scripting' started by LutherP, Mar 4, 2010.

  1. LutherP

    LutherP

    Joined:
    Feb 24, 2010
    Posts:
    8
    Maybe I'm jsut too tired to figure this out but I can't even think of where to begin with this code.

    What I want is to get a projectile to fire towards the mouse's x and y coordinates, but in 3d space. Like in a light gun game, only instead of the beam indicating where to fire it's the mouse. The problem is I can't think how to make the velocity/angle work out for it other than just using Math Clamp and trial and error testing. I know there must be a more elegant way than that.

    Here's my code so far (I've cribbed most of it from the FPS Tutorial and a few other places around the board)
    Code (csharp):
    1.  
    2. var projectile : Rigidbody;
    3. var initialSpeed = 200.0;
    4. var handReloadTime = 0.5;
    5. var torsoReloadTime = 1.5;
    6. var handAmmoCount = 20;
    7. var torsoAmmoCount = 20;
    8. private var handLastShot = -10.0;
    9. private var torsoLastShot = -10.0;
    10.  
    11. function Update () {
    12.     //Hand Gun Shoots
    13.     if(Input.GetButtonDown("HandWeapon")) {
    14.         if (Time.time > handReloadTime + handLastShot  handAmmoCount > 0) {
    15.             fireHandWeapon();
    16.             handAmmoCount--;
    17.             handLastShot = Time.time;
    18.         }
    19.     }
    20.     //Torso Gun Shoots
    21.     if(Input.GetButtonDown("TorsoWeapon")) {
    22.         if (Time.time > torsoReloadTime + torsoLastShot  torsoAmmoCount > 0) {
    23.             fireTorsoWeapon();
    24.             torsoAmmoCount--;
    25.             torsoLastShot = Time.time;
    26.         }
    27.     }
    28. }
    29.  
    30. function fireHandWeapon(){
    31. //Angle accordin to the Mouse X and Y axis
    32. print("Pew!");
    33. var instantiatedProjectile : Rigidbody = Instantiate (projectile, transform.position, transform.rotation);
    34. instantiatedProjectile.velocity = transform.TransformDirection(Vector3 (initialSpeed,0, 0));
    35. Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
    36. }
    37.  
    38. function fireTorsoWeapon(){
    39. //Angle according to the Mouse Y Axis
    40. print("Ka-blam!");
    41. var instantiatedProjectile : Rigidbody = Instantiate (projectile, transform.position, transform.rotation);
    42. instantiatedProjectile.velocity = transform.TransformDirection(Vector3 (initialSpeed,0, 0));
    43. Physics.IgnoreCollision(instantiatedProjectile.collider, transform.root.collider);
    44. }
    45.  
    Thanks for the help guys (and girls).
     
  2. refardeon

    refardeon

    Joined:
    Feb 19, 2010
    Posts:
    51