Crossing the Road
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 82 of 85.
A hopper waits at the edge of a busy road. Cars come in from the left in three lanes and drive across. The player hops forward or back one lane at a time with the up and down arrows, and has to time each hop to reach the far side. A car that touches the hopper sends it back to where it started.
Write the whole game in one script, Crossing, on the hopper.
Challenge
HardStart the road crossing game: the hopper hops lane by lane.
- In
Start(), savetransform.positionin aVector3 startfield. - Each press of the up arrow hops 2 units along +z. The down arrow hops 2 back, only while z is above
start.z. - When z reaches
4, logYou made it!and setenabled = false.
Press Play and hop to the far side. Then Check.
Try it yourself
using System.Collections.Generic;
using UnityEngine;
public class Crossing : MonoBehaviour
{
[SerializeField] private GameObject carPrefab;
[SerializeField] private float[] lanes;
[SerializeField] private float spawnEvery = 1f;
[SerializeField] private float carSpeed = 5f;
void Start()
{
}
void Update()
{
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground