Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

2D z rotation in specific angel / launching object

Discussion in '2D' started by si0ty, Jul 16, 2019.

  1. si0ty

    si0ty

    Joined:
    Jun 28, 2019
    Posts:
    4
    Helly Guys,

    little disclaimer here im a total noob and i'm sorry if my attempt and code are completly bs.

    I want a flat sprite (just like a block) to launch an object on top of it in to the air. For this I setted up a HingeJoint2D with a limited angle.
    It should work like so: the default position of the sprite is an angle of 0 degrees. when I press the ArrowDown key it slowly rotates down on the z axis. As soon as I leave the ArrowDown key the Sprite snaps upwards into his default position and launches off the object on top of it.

    It seemed pretty doable for me but i'm pretty stuck and really cant find a solution on the internet.
    Would appreciate any tips and general tips on this - thanks!

    This is what I got:

    Code (CSharp):
    1.   public float speed = -100f;
    2.     // Use this for initialization
    3.     void Start() {
    4.  
    5.         HingeJoint2D hinge = GetComponent<HingeJoint2D>();
    6.         bool enabled = new bool();
    7.         hinge.useMotor = enabled;
    8.            
    9.     }
    10.  
    11.     // Update is called once per frame
    12.     void Update() {
    13.  
    14.         if (Input.GetKey(KeyCode.DownArrow)) {
    15.             transform.Rotate(0, 0, speed * Time.deltaTime);
    16.  
    17.             enabled = false;
    18.         }
    19.     }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    1,833
    Rule#1 : Never ever change the transform when using physics components as you're just stomping over their single responsibility which is to control the transform. If you're using physics then communicate with the physics components directly.

    If you want to rotate then rotate the Rigidbody2D by applying torque, setting the angular velocity or use Rigidbody2D.MoveRotation. Doing this means that when the simulation runs it can solve the rigidbody2d pose with respect to other forces such as joints. Just setting the transform just instantly teleports the body to another pose and nothing is solved; indeed it's possible for you to set a pose which is way outside any limits so then the physics has to try to solve that. On top of that, doing this each frame makes it even worse because the physics is constantly getting overridden.
     
  3. si0ty

    si0ty

    Joined:
    Jun 28, 2019
    Posts:
    4
    Thanks!! That helped a lot. Controlling the motor of the HingeJoint2D was the solution.