Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

TPS Gun aiming at target (fixed)

Discussion in 'Scripting' started by sasa_dev, May 6, 2020.

  1. sasa_dev

    sasa_dev

    Joined:
    Apr 4, 2020
    Posts:
    10
    Hello guys, I've been coding a third person shooter of which the aiming is mouse-based. Just like in Fortnite for example. I have coded a simple gun aiming towards the mouse and I calculated the rotation with Atan2. I restricted the rotation to the y axis and it works. However, I had to determine which way the player is facing so the gun points at the right direction. Now the problem is, it's more like a hacky code and when the player rotates to the right, there are angles where the gun still points the wrong direction. What is the best way to do this?

    Here's my code and below a video demonstration:
    Code (CSharp):
    1.  
    2. Vector3 difference = crossbar.position - currentGun.position;
    3. float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
    4. if (headingAngle > 0f && headingAngle <= 180f) {
    5.    currentGun.localRotation = Quaternion.Euler(gunRotation.x + 180, gunRotation.y + 180, -rotationZ);
    6. } else {
    7.    currentGun.localRotation = Quaternion.Euler(gunRotation.x, gunRotation.y, rotationZ);
    8. }
    9.  
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    Couldnt you just make the gun LookAt() some position in front of the player (known through player.forward), or a point some distance behind the crosshair (using a raycast from crosshair position screen to world)?
    That would remove all extra calculations and room for error.
     
  3. sasa_dev

    sasa_dev

    Joined:
    Apr 4, 2020
    Posts:
    10
    I think the problem is because of the rotation point. It kinda rotates from the center so it's really weird wenn I'm rotating the player. I tried it with LookAt, however the rifle then faces from it's center to the target and not from the muzzle
     
  4. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Your gun model itself is rotated strangely then. You will want to go back to blender and fix the rotation so that z+ is the direction the barrel of the gun is facing. Either that or you will need to always apply a correctional rotation to get the gun pointed property.
     
    Yoreki likes this.
  5. sasa_dev

    sasa_dev

    Joined:
    Apr 4, 2020
    Posts:
    10
    Thanks a ton dude, the problem was due to the weird rotation from the model itself. I then fixed the code with a short and clean transform.LookAt(crosshair);
     
    PraetorBlue likes this.