- Home /
Question by
Grey_Wolf9 · Oct 21, 2019 at 01:33 AM ·
c#unity 2dtimer
Using the timer as a condition
I am making an interactive game that uses a sensor as an input to the game. As part of my initial prototype I used the analog values from the sensor as a condition in an if statement. But now I want to use the time that the sensor is pressed for as a condition instead of the actual analog values to move the player from one position to another. I have a working timer and player script, and have attached both. This is the player controller script that takes the information from the sensor:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class PlayerController : MonoBehaviour
{
SerialPort sp = new SerialPort("\\\\.\\COM4", 9600);
//player = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
public float Speed;
public Vector2 height;
public float xMin, xMax, yMin, yMax;
void Awake()
{
//player = GameObject.FindWithTag("Player");
}
void Start()
{
if (!sp.IsOpen)
{ // If the erial port is not open
sp.Open(); // Open
}
sp.ReadTimeout = 250; // Timeout for reading
}
void Update()
{
if (sp.IsOpen)
{ // Check to see if the serial port is open
try
{
string value = sp.ReadTo("EOL"); //Read the information
float amount = float.Parse(value);
//transform.Translate(Speed * Time.deltaTime, 0f, 0f); //walk
if (amount > 25f)//(Input.GetKeyDown(KeyCode.Space)) //jump
{
GetComponent<Rigidbody2D>().AddForce(height, ForceMode2D.Impulse);
}
GetComponent<Rigidbody2D>().position = new Vector3
(
Mathf.Clamp(GetComponent<Rigidbody2D>().position.x, xMin, xMax),
Mathf.Clamp(GetComponent<Rigidbody2D>().position.y, yMin, yMax)
);
}
catch (System.Exception)
{
}
}
void ApplicationQuit()
{
if (sp != null)
{
{
sp.Close();
}
}
}
}
}
This is the timer script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour
{
public int timeLeft = 5;
public Text countdownText;
// Use this for initialization
void Start()
{
StartCoroutine("LoseTime");
}
// Update is called once per frame
void Update()
{
countdownText.text = ("Time Left = " + timeLeft);
if (timeLeft <= 0)
{
StopCoroutine("LoseTime");
countdownText.text = "Times Up!";
Invoke("ChangeLevel", 0.1f);
}
}
IEnumerator LoseTime()
{
while (true)
{
yield return new WaitForSeconds(1);
timeLeft--;
}
}
void ChangeLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
Any assistance would be most appreciated.
Comment