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. Dismiss Notice

Question Sprite bug(?) Rotating a weapon, buggy squares

Discussion in '2D' started by s-martin, Aug 13, 2023.

  1. s-martin

    s-martin

    Joined:
    Apr 2, 2022
    Posts:
    2
    Hello! I'm trying to do a shooter where the weapon rotates "alone" to the enemy position, for that:
    * I created 1 player and 1 enemy, the white squares
    * Inside the Player, I created the weapon as another black square and made it a rectangle (Sprite). To be able to rotate it in a side, I also made it as a child of an emty object (Weapon Pivot).

    The issue is, when I press play the sprite becomes almost invisible except for a line. I believe the script (equipped inside Weapon Pivot) works fine because when I press play, the line rotates in direction of the other white square (the enemy) BUT why is it showing like this?

    Unity arma.png

    Thx for the attention!!
     
  2. venediklee

    venediklee

    Joined:
    Jul 24, 2017
    Posts:
    143
    Are your sprites on the same Z value? It looks like the weapon thingy is rotating in 3D

    To see if your code works fine, rotate the weapon by hand in the inspector and compare the rotation with the scripts results. IIRC only the y rotation needs to change for this.

    Also make sure the pivot of the weapon is at the base so it rotates “physically accurately”
     
    s-martin likes this.
  3. s-martin

    s-martin

    Joined:
    Apr 2, 2022
    Posts:
    2
    Venediklee tyvm for the reply! You are right, the Z axis was failing.

    I changed the script for the function RotateTowards: https://docs.unity3d.com/ScriptReference/Vector3.RotateTowards.html
    The result is the same. I have no clue how to modify only the Z axis letting the X/Y axis alone. If you or any kind soul could help with an explanation or link would be awsome!

    Thx again for the attention
     
  4. venediklee

    venediklee

    Joined:
    Jul 24, 2017
    Posts:
    143
    You can calculate it manually I guess

    1. Find the vector from the weapon to target = aimVector
    2. Calculate the arc tangent with atan2(aimVector.y, aimVector.x) = alphaAngle -- this is in radians
    3. Set rotation's euler Z to alphaAngle * Mathf.Rad2Deg
    I wrote this based off my answer here, hopefully there is no error


    Maybe this will work too idk https://docs.unity3d.com/ScriptReference/Vector2.SignedAngle.html

    Make sure the pivot of the weapon is actually at its base so it pivots from that point instead of the center point