Created
June 26, 2023 13:50
-
-
Save kurtdekker/795ac387027c510548bcb635fac0caff to your computer and use it in GitHub Desktop.
Lane-based motion in the X- and Z- coordinate space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
// @kurtdekker - lane-based mover | |
// | |
// To use: | |
// Drop this on your player object | |
// Move your camera to see it go into the distance (see note about 2D below) | |
// press PLAY | |
// use A and D to change lanes | |
public class LaneMover : MonoBehaviour | |
{ | |
private int laneNumber; | |
const int MaxLanes = 3; | |
const float LaneWidth = 2.0f; | |
const float LaneZeroXPosition = -LaneWidth * (MaxLanes - 1) / 2.0f; | |
const float LateralLaneMoveSpeed = 10.0f; | |
const float ForwardPlayerSpeed = 5.0f; | |
void Update() | |
{ | |
// gather input to change lanes | |
if (Input.GetKeyDown( KeyCode.A)) laneNumber--; | |
if (Input.GetKeyDown( KeyCode.D)) laneNumber++; | |
// now guard laneNumber to 3 lanes | |
if (laneNumber < 0) laneNumber = 0; | |
if (laneNumber > MaxLanes - 1) laneNumber = MaxLanes - 1; | |
// where should we be for this lane? | |
float laneXPosition = laneNumber * LaneWidth + LaneZeroXPosition; | |
// working copy | |
Vector3 position = transform.position; | |
// compute desired lateral position | |
position.x = Mathf.MoveTowards( position.x, laneXPosition, LateralLaneMoveSpeed * Time.deltaTime); | |
// move the player downrange (change this to position.y for 2D games!) | |
position.z += ForwardPlayerSpeed * Time.deltaTime; | |
// of we go (replace with Rigidbody/Rigidbody2D.MovePosition() if using physics!) | |
transform.position = position; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment