For my tile puzzle game, how can i have the player cube only step on a tile once and if they step on the tile a second time the game will be lost?
I currently have a tile play area where the player can move 1 unit in 4 directions, I have tried a lot to get this to work and so far no luck, I am using a Raycast to detect each tile as the player is on it, and i have the tile change to blue when it is stepped on, but if it is stepped on a second time i would like it to turn to red. I am aware of OnTriggerEnter and Exit but I feel like it would be more convenient to use a Raycast for this to happen.
Thanks in advance for any help.
Answer by Veerababu.g · Mar 28, 2016 at 04:58 AM
public boo hasfirstJump = false;
void OnTriggerEnter(collider other){ if(other.compareTag("playerTag"){ if(hasfirstJump == false){ hasfirstJump = true; //return }else //write your code for level faild } }
Answer by Addie · Mar 28, 2016 at 05:34 AM
@Inf1n1teZer0 this might help
using UnityEngine;
using System.Collections;
public class Tile : MonoBehaviour
{
public Player player;
public bool steppedOn = false;
public int steppedCount = 0;
void Start ()
{
player = FindObjectOfType<Player>();
}
void Update ()
{
if(steppedCount == 1 && player.gameOver == false)
{
transform.GetComponent<Renderer>().material.color = Color.yellow;
}
else if(steppedCount == 2 && player.gameOver == false)
{
transform.GetComponent<Renderer>().material.color = Color.red;
StartCoroutine(GameOver());
}
}
private IEnumerator GameOver()
{
player.gameOver = true;
Debug.Log("GAME OVER");
while(player.gameOver == true)
{
foreach(Tile allTiles in player.allTiles)
{
allTiles.GetComponent<Renderer>().material.color = Color.red;
yield return new WaitForSeconds(0.1f);
allTiles.GetComponent<Renderer>().material.color = Color.yellow;
}
}
}
}
place the top script on all the tile gameobjects and place the player script on your player gameobject
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
public bool gameOver = false;
private Tile hitTile;
public Tile[] allTiles;
void Start ()
{
allTiles = FindObjectsOfType<Tile>();
}
void Update ()
{
if(gameOver == false)
{
CheckTileRay();
PlayerMovement();
}
}
void CheckTileRay()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, 1f))
{
if (hit.collider)
{
hitTile = hit.collider.GetComponent<Tile>();
if (hitTile.steppedOn == false)
{
hitTile.steppedCount += 1;
hitTile.steppedOn = true;
}
}
}
}
void PlayerMovement()
{
if (Input.GetKeyDown(KeyCode.A))
{
hitTile.steppedOn = false;
transform.position += new Vector3(-1, 0, 0);
}
if (Input.GetKeyDown(KeyCode.D))
{
hitTile.steppedOn = false;
transform.position += new Vector3(1, 0, 0);
}
if (Input.GetKeyDown(KeyCode.W))
{
hitTile.steppedOn = false;
transform.position += new Vector3(0, 0, 1);
}
if (Input.GetKeyDown(KeyCode.S))
{
hitTile.steppedOn = false;
transform.position += new Vector3(0, 0, -1);
}
}
}