I’m making an RPG random Battle system and I would love to have the player enter a battle after taking a certain number of steps.
My code is:
using UnityEngine;
using System.Collections;
public class Battle : MonoBehaviour
{
int Steps;
bool Go;
void Counter()
{
Steps = Steps + 10;
if (Steps == 100)
{
Go = true;
}
if (Go = true)
{
Application.LoadLevel("Battle1");
}
}
}
How do I make it so that when I press KeyCode.UpArrow, Left, Right Or Down Steps adds 1?
With if You check if there was button pressed and as argument you pass which key exacly was pressed (in this case it’s Space).
If it’s true ( if space was pressed) then add steps. (Steps++ == Steps=Steps+1;)
You do not want to count steps this way. Yes, the player moves when the key is pressed down, however the player does not move forward by tapping the up key. You need to work out a way that best suits you to count the steps of the player.
A suggestion would be to get the position of the player when the game starts then add it to slot one. Now in slot one we have (0,0,0) then in update we get the position again and compare it with the previous position:
(0,0,0) → (0,2,0)
We pass this to a function to compare each vector and count the difference. So say each step equalled “0.5” then the StepCount function would see (0 steps, 4 steps, 0 steps).
The StepCount function then replaces the previous position with the current position and repeats.
using UnityEngine;
using System.Collections;
public class StepCounter : MonoBehaviour {
public Vector3 lastPosition;
public float stepLength;
float xSteps;
float ySteps;
public float stepsTaken;
public bool countingSteps = true;
// Use this for initialization
void Start ()
{
lastPosition = gameObject.transform.position;
StartCoroutine (StepCountUpdate ());
}
private IEnumerator StepCountUpdate()
{
while (countingSteps == true)
{
yield return new WaitForSeconds(4);
Vector3 currentPos = gameObject.transform.position;
StepCount (currentPos);
}
}
//Counts the steps made
public void StepCount(Vector3 currentPosition)
{
// calculates the steps made in the X Axis.
float x = currentPosition.x - lastPosition.x;
x = Mathf.Round(x);
if (x < 0)
{
xSteps = x / stepLength;
xSteps = Mathf.Abs (xSteps);
}
else
{
xSteps = x / stepLength;
}
// calculates the steps made in the X Axis.
float y = currentPosition.y - lastPosition.y;
y = Mathf.Round(y);
if (y < 0)
{
ySteps = y / stepLength;
ySteps = Mathf.Abs (ySteps);
}
else
{
ySteps = y / stepLength;
}
stepsTaken = stepsTaken + xSteps + ySteps;
lastPosition = currentPosition;
}
}