How to make my stick rotating after bouncing with button long pressed?

Viewed 54

Basically I want to make bouncing stick and rotate control, with the left-right button.i'm facing an issue that the rotate not good as I expected because it won't follow my button like being affected by something after bouncing,

I'm using 2d physics material with friction = 1 and Bounciness = 0.9797 for perfect bouncing also attached to rigidbody2d.

I don't know, should I attach it on collider?

here my Player control Script:

public Rigidbody2D r2d;

public float vertical;
public float horizontal;
public Joystick joystick;

private void Start() {
    r2d = gameObject.GetComponent < Rigidbody2D > ();
    joystick = FindObjectOfType < Joystick > ();
}

private void Update() {
    Movement();
}

public void Movement() {
    r2d.velocity = r2d.velocity.normalized * 7f;

    //horizontal = joystick.Horizontal;
    //vertical = joystick.Vertical;

    //if (horizontal == 0 && vertical == 0)
    //{
    //    Vector3 curRot = transform.localEulerAngles;
    //    Vector3 homeRot = transform.localEulerAngles;

    //    transform.localEulerAngles = Vector3.Slerp(curRot, homeRot, Time.deltaTime * 2);
    //}
    //else
    //{
    //    transform.localEulerAngles = new Vector3(0f, 0f, Mathf.Atan2(horizontal, vertical) * -180 / Mathf.PI);
    //}
}

public Vector3 target;
public float rotationSpeed = 10f;
public float offset = 5;

public void turnLeft() {
    Vector3 dir = target - transform.position;
    float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
    transform.rotation = Quaternion.Slerp(transform.rotation, -rotation, rotationSpeed * Time.deltaTime);
}

public void turnRight() {
    Vector3 dir = target - transform.position;
    float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
    Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
    transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}
1 Answers

Whenever there is a Rigidbody/Rigidbody2D involved you do not want to manipulate anything via the .transform component!

This breaks the physics, collision detection and leads to strange movements basically the transform "fighting" against physics for priority.

What you rather want to do would be e.g. adjusting the Rigidbody2D.angularVelocity

public void turnLeft()
{
    // Note that Time.deltaTime only makes sense if this is actually called every frame!
    r2d.angularVelocity -= rotationSpeed * Time.deltaTime;
}

public void turnRight()
{
    r2d.angularVelocity += rotationSpeed * Time.deltaTime;
}
Related