Search code examples
c#unity-game-enginegame-enginegame-physicsgame-development

Physics In Unity Game (pendulum effect)


So, i don't really know how to search for a answer to my question, i am working as a game developer for a freelance and my task was to do a "pendulum platform", That's the concept:

enter image description here

I tried a lot of different aproaches, like, for example setting collision boxes in the sides of the platform and when the player enter in the collision box, the platform will move like a pendulum.

But, i always ran into a lot of glitches, and when i managed to solve all of them, the movement felt unnatural.

Here is one of the ways i was trying :

public IEnumerator RotatesTowardsLeft()
{
    while (transform.parent.eulerAngles.z < 25 || transform.parent.eulerAngles.z >= 330)//25
    {
        transform.parent.eulerAngles += new Vector3(0, 0, speed);
        yield return new WaitForSeconds(0.01f);
    }
    currentDirection = Directions.Left;
}

public IEnumerator RotatesTowardsRight()
{
    while (transform.parent.eulerAngles.z > 335 || transform.parent.eulerAngles.z < 30)
    {
        transform.parent.eulerAngles += new Vector3(0, 0, -speed);
        yield return new WaitForSeconds(0.01f);
    }
    currentDirection = Directions.Right;
}

So, if anyone could help me, it would mean a lot, because i feel like i am running out of options...


Solution

  • Try using physics objects, and attaching a ConfigurableJoint to your object. (If you're working in 2D, use DistanceJoint2D) Then you can choose a location for the joint to attach to above it, and it should give you the effect you desire without a bunch of code. Keep in mind, if you are in 3D, there will be a little extra work to set up the ConfigurableJoint, like limiting some of the axes and spring force.

    Hope this helps!