Moving Platforms
Part of the Building Real Games section of Coddy's Unity journey. Lesson 49 of 56.
Challenge
MediumThe blue platform should glide back and forth over the gap. Keep everything from the last lesson.
Fill in MovingPlatform:
- Two fields the Inspector sets,
distance(3) andspeed(1.5), and apublic Vector3 delta. - It glides from where it starts to
distanceunits along +x atspeedunits per second, then back to its start, and so on for ever. - Every frame,
deltais how far it moved in that frame: its position after the move minus its position before.
A CharacterController is not carried by what it stands on: on a moving platform it stays where it is, and the platform slides away under it. Moving its transform.position along does not work either: the controller's next Move starts from where the physics last saw it, and undoes the change. Make Player ride along:
- Add
OnControllerColliderHit. When the hit's normal points up (hit.normal.yabove 0.5: the player stands on it) and the object has aMovingPlatform, keep that platform in a field. - In
Update, add that platform'sdeltato the motion passed tocontroller.Move, then forget the platform (set the field tonull). TheMovecall finds it again for as long as the player stands on it.
Press Play, jump onto the platform and ride it, then Check.
Try it yourself
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
// A later lesson fills this in: a platform that glides back and forth.
}
All lessons in Building Real Games
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input Swap