Moving Platforms in Unity
--
It’s time to make a platform move independently
Configuring the MovePlatform gameobject
- Select the MovePlatform gameobject to move and attach a
MovePlatform
script to it - Create 2 empty game objects (PointA, PointB) and assign each one a position on the
x
axis between whichMovePlatorm
will move - Declare these variables in the
MovePlatform
script:Transform PointA, PointB --- bool MoveRight, MoveLeft
- In
Start()
:transform.position = pointA.position;
moveToRight = true; - In
Update()
move the platform to the right (PointB) and whenVector3.Distance(transform.position, pointB.position) < 0.01f)
, move it to the left (PointA)
Explanation
- The objective is to move the platform between 2 points
- The platform will start at PointA position with
moveToRight
= true - To move it, we will use
Vector3.MoveTowards()
that requires a starting point, a target point and a step (float) value (for instance, speed * Time.deltaTime) - To switch between the 2 points, we will use the
MoveRight
andMoveLeft
bool variables
If moveRight
= true, it will move towards the PointB position.
When distance < 0.01f
, moveRight
= false and moveLeft
= true
If moveLeft
= true, the platform will move towards PointA.
If the distance < 0,01f
, moveLeft
= false and moveRigth
= true
Fixing jittering when the player is moving on the platform
After creating the mechanic of moving player with platform, in Play mode (scene tab) there is a little jitter effect.
It is due to a conflict between updating information in MovePlatform (non physics gameobject) and Player (CharacterController — physics) gameobject
To solve it, in MovePlatform
script, change the Update()
method to FixedUpdate()