# How to tilt an object(2D) after collision and the rotate continuously

I am having trouble rotating and object after collision. The object only transforms to the given angle of rotation once and stops. I would like to achieve in a way that after it has collided with the player object it rotates continuously till its killed after exiting the screen. The OnCollisionEnter2D(Collision2D collision) can't achieve this.

How can I achieve it using the FixedUpdate function?

Here is the code:

namespace Assets.scripts
{
public class Barmovementscript : MonoBehaviour
{
public float Tilt;

private void FixedUpdate()
{
}

// upon collision the object rotates in a clockwise direction.
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.collider.tag == "Player")
{
Tilt += Time.deltaTime * -10;
gameObject.transform.rotation = Quaternion.Euler(0, 0, Tilt);
}
}
}
}

• It's not clear to me how this post differs from the question you asked yesterday. If you want to update your question with new information, or want to narrow the kind of solution you're looking for, you can use the "edit" button on the original post. – DMGregory Dec 14 '16 at 16:22

Simply make the collision event change a Boolean. And rotate your object if the Boolean is true in the fixed update

Keep a float called, say, "spin," indicating angular velocity. In your Update method, update your Tilt with Spin, and recalculate your quaternion.

(I haven't tried to compile this.)

namespace Assets.scripts
{
public class BarMovementScript : MonoBehaviour
{
// angular velocity
public float Tilt;
public float Spin;

private void FixedUpdate()
{
if (0.f != Spin)
{
Tilt += Spin * Time.deltaTime;
gameObject.transform.rotation = Quaternion.Euler(0, 0, Tilt);
}
}

// upon collision the object rotates in a clockwise direction.
void OnCollisionEnter2D(Collision2D collision)
{
if ("Player" == collision.collider.tag)
{
Spin = -10.f;
}
}
}
}


For a slightly cleaner (IMHO) approach, just use Verlet integration. In FixedUpdate(), get the difference between current tilt and that in the previous frame, add it to Tilt, and update your transform:

(Again, I haven't compiled this.)

namespace Assets.scripts
{
public class BarMovementScript : MonoBehaviour
{
// angular velocity
public float Tilt;
private float m_prevTilt;
private float m_prevDT = 1.f / 60.f; // lame hack, assume 60FPS initially.

private void FixedUpdate()
{
var dTheta = Tilt - m_prevTilt;
var dt = Time.deltaTime;

if (0.f != dTheta && 0.f != m_prevDT)
{

Tilt += dTheta * dt / m_prevDT;

gameObject.transform.rotation = Quaternion.Euler(0, 0, Tilt);

m_prevTilt = Tilt;
}

m_prevDT = Time.deltaTime;

}

// upon collision the object rotates in a clockwise direction.
void OnCollisionEnter2D(Collision2D collision)
{
if ("Player" == collision.collider.tag)
{
Tilt = Time.deltaTime * -10;
m_prevDT = Time.deltaTime;
}
}
}
}