- Home /
Move Object a direction with one button and move the object back with the same button?
Basically like Swing Copters where you tap the screen the characters flies right, then when you tap again he switches and flies left, like that. Im having trouble getting that to work. I'm getting stuck because my character moves one way and I have to hold the space bar to move him back or it won't go the direction I want to at all. Any help is appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swingplay : MonoBehaviour
{
public float speed = 3f;
private bool gameStart = false;
public bool goingRight = false;
void FixedUpdate()
{
if (Input.GetKey("space") && goingRight == false)
{
goingRight = true;
}
if (Input.GetKeyDown("space") && goingRight == true)
{
goingRight = false;
}
if (goingRight == true)
{
transform.Translate(-Vector3.left * speed * Time.deltaTime);
}
else
{
transform.Translate(-Vector3.right * speed * Time.deltaTime);
}
}
//transform.Translate(-Vector3.left * speed * Time.deltaTime);
}
Answer by cstooch · Jun 26, 2017 at 05:27 AM
Unrelated to your issue.. but FixedUpdate is meant for physics.. you should have this stuff in a regular Update function.
As far as your issue... I'm a little confused on the logic you're trying to accomplish here:
if (Input.GetKey("space") && goingRight == false)
{
goingRight = true;
}
if (Input.GetKeyDown("space") && goingRight == true)
{
goingRight = false;
}
Me, I'd just do it like this:
If (Input.GetKeyDown("space")) // or Input.GetKeyUp if you want them to have to release the key..
{
goingRight = !goingRight; // this toggles this bool
}
Then just continue doing the "if (goingRight == true)" stuff afterwards.
Thanks, sorry for the late reply, this definitely helped and fixed my problem. I'm new to Unity and program$$anonymous$$g so this may have seen like an obvious question but I was stumped. Thanks again for answering! $$anonymous$$eans a lot
No worries! Glad this worked for you. Don't be afraid to ask questions here ever. There are certainly a lot more basic questions being asked here each day.. and plus, everyone here has something to learn in Unity, myself definitely included. I'm far from an expert in Unity, but I've been program$$anonymous$$g for quite some time. But I learn a lot here each day.
Anyways, good luck with your project(s)!