Movement on multiple rails.

Hi,

I’m making a simple shooter game. Player will be able to move only in x axis, staying still on y and z axis.
I have scrolling textures to make it look like it’s moving toward.

This is what I’m trying to accomplish:

When I press left, the player moves (warps it’s position) say, 4 units to the left on x-axis(relative to player position)
and pressing right player moves 4 units to right on x-axis.

It should be able to move on 5~ rails (restricting the players movement to -10x and 10x), evading incoming obstacles and collecting points.

I’m beginner with unity. Here’s one screen of the game.
http://dl.dropbox.com/u/61562397/screen.jpg

If you press left, just decrease a variable, rail by one. If you press right, increase rail by one. Position the object according to the rail variable. Use if statements or Mathf.Clamp to make sure the rail variable doesn’t go outside allowed values. The movement would be restricted to -8 and 8 (-8, -4, 0, 4, 8).

public class Rails : MonoBehaviour
{
	[HideInInspector]
	public int rail = 0;
	public float gap = 4;

	void Update()
	{
		int oldRail = rail;
		if (Input.GetKeyDown(KeyCode.LeftArrow))
			rail = Mathf.Clamp(--rail, -2, 2);
		if (Input.GetKeyDown(KeyCode.RightArrow))
			rail = Mathf.Clamp(++rail, -2, 2);
		if (rail != oldRail)
			SendMessage("OnRailChanged", rail, SendMessageOptions.DontRequireReceiver);
	}

	void OnRailChanged(int rail)
	{
		// Called whenever we changed rail.
		// Good place to add sound effects etc.
		transform.localPosition = new Vector3(rail * gap, 0, 0);
	}
}

Just use Input.GetAxisRaw to find your Horizontal values and decrease or increase transform.position.x accordingly. To warp from ‘rail’ to ‘rail’, try:

function Update () {
    if (Input.GetButtonDown("Horizontal")) {
    		transform.position.x = transform.position.x + ((Input.GetAxisRaw("Horizontal")) * 4);
    		transform.position.x = Mathf.Clamp(transform.position.x, -10, 10);
    	}
}

There is an even cooler way of doing this, which is also simpler (I think at least) and looks a hell of a lot better … :slight_smile: This allows for free movement on the x axis:

function Update () {
	var pos : int = (Input.GetAxisRaw("Horizontal")) * 4;
	transform.position.x = Mathf.Lerp(transform.position.x, transform.position.x + pos, Time.deltaTime * 5.0);
	transform.position.x = Mathf.Clamp(transform.position.x, -10, 10);
}

That uses a Lerp for smooth flying across the screen. I tried to do a Lerp for smooth travelling across your rails, but it ended up not working and I didn’t have enough time … Sorry :confused: If that’s what you want, just experiment with Input.GetButtonDown(“Horizontal”) and Mathf.Lerp … :slight_smile:

Hope that helps, Klep

P.S. Thanks for that question! I learnt a lot that I didn’t know beforehand (especially in terms of GetAxisRaw)! This is why i love UA … I learn things even when I’m answering the questions … :slight_smile: