- Home /
Fixing Diagnol Speed Boost C#
I am running into a problem where a function is being called over and over again, however I only want it to be called once each time an input is detected. That function name is DiagFix that you can see in my code below
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
public GameObject GamePiece;
public float speed = 0.4f;
public bool dinitiated = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if ((Input.GetButton ("Forward") && Input.GetButton ("SLeft")) ||
(Input.GetButton ("Forward") && Input.GetButton ("SRight")) ||
(Input.GetButton ("Backward") && Input.GetButton ("SLeft")) ||
(Input.GetButton ("Backward") && Input.GetButton ("SRight"))) {
DiagFix();
}
Vector3 minusx = new Vector3(-speed,0,0);
Vector3 plusx = new Vector3(speed,0,0);
Vector3 minusz = new Vector3(0,0,-speed);
Vector3 plusz = new Vector3(0,0,speed);
if (Input.GetButton ("Forward")) {
if (GamePiece.transform.position.z < 24.5f) {
GamePiece.transform.position += plusz;
}
}
if (Input.GetButton ("Backward")) {
if (GamePiece.transform.position.z > 0.5f) {
GamePiece.transform.position += minusz;
}
}
if (Input.GetButton ("SLeft")) {
if (GamePiece.transform.position.x > 0.5f) {
GamePiece.transform.position += minusx;
}
}
if (Input.GetButton ("SRight")) {
if (GamePiece.transform.position.x < 24.5f) {
GamePiece.transform.position += plusx;
}
}
}
void DiagFix () {
if( dinitiated = false ) {
dinitiated = true;
speed = speed / 4;
} else {
Comment
Answer by robertbu · Oct 27, 2013 at 08:39 PM
This is a ugly little probelm that I don't see an elegant fix. You can solve it by replacing each of the main clauses in your 'if' statement with two statements, checking the 'Down' state for one or the other of the two buttons:
if ((Input.GetButtonDown ("Forward") && Input.GetButton ("SLeft")) ||
(Input.GetButton ("Forward") && Input.GetButtonDown ("SLeft")) ||
(Input.GetButtonDown ("Forward") && Input.GetButton ("SRight")) ||
(Input.GetButton ("Forward") && Input.GetButtonDown ("SRight")) ||
(Input.GetButtonDown ("Backward") && Input.GetButton ("SLeft")) ||
(Input.GetButton ("Backward") && Input.GetButtonDown ("SLeft")) ||
(Input.GetButtonDown ("Backward") && Input.GetButton ("SRight")) ||
(Input.GetButton ("Backward") && Input.GetButtonDown ("SRight"))) {