- Home /
How to make object go from A to B and from B to A with same key
Hello! Im trying to make my first game, and i need some help on how to make my object move from A to B when i press "a", and from B to A when i press "a" again. I have found a script that moves my object from A to B, but i can't figure out how to make it go from B to A when i press "a" again.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lerp : MonoBehaviour {
public GameObject player;
private Vector3 pos1;
private Vector2 pos2;
private float distance = 4.7f;
private float time = 0.05f;
private float currentTime = 0;
private bool keyHit = false;
// Use this for initialization
void Start () {
pos1 = player.transform.position;
pos2 = player.transform.position + Vector3.right*distance;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown ("a")) { keyHit = true; }
if (keyHit == true)
{
currentTime += Time.deltaTime;
if (currentTime >= time) { currentTime = time;
}
float Perc = currentTime / time;
player.transform.position = Vector3.Lerp(pos1, pos2, Perc);
}
}
}
This is the general notion of a toggle. A toggle is an on/off state, like a momentary push button. It goes on if it's off, it goes off if it's on.
You'll need a bool. Initialize it (true or false is your choice). When true, for example, the object is moving from A to B, but when false it should move from B to A. Every "a" you hit, check the toggle and do accordingly, but flip the toggle as you do, so the next time, you do the other thing.
Answer by MT369MT · Jul 11, 2018 at 06:13 PM
Hi, you could add a variable to know in which position you are for example:
int currentPos
if (player.transform.position == pos1)
{
currentPos = 1;
}
else if (player.transform.position == pos2)
{
currentPos = 2;
}
else
{
currentPos = 0;
}
if (Input.GetKeyDown ("a")) {
keyHit = true;
}
if (keyHit == true)
{
currentTime += Time.deltaTime;
if (currentTime >= time)
{
currentTime = time;
}
float Perc = currentTime / time;
if (currentPos == 1)
{
player.transform.position = Vector3.Lerp(pos1, pos2, Perc);
}
else if (currentPos == 2)
{
player.transform.position = Vector3.Lerp(pos2, pos1, Perc);
}
}
}
Then you must probably set keyHit to false again when the player reached the Pos. Ask if you need more.
Answer by stavabu · Jul 13, 2018 at 01:19 PM
Hey @MT369MT! Thanks for the tips. How do i make the var know if the object is in pos1 or pos2? I'm very new at coding, just started a couple days ago :/
Create two new variables called pos1 and pos2. Assign them to pos1 = new Vector2(-2.35, 0) and pos2 = new Vector2(2.35, 0)
Your answer
Follow this Question
Related Questions
Code working on wrong axis. 1 Answer
how to find a point(vector2) between two points(Vector2) of a line (line renderer) 2 Answers
Script to make Camera follow the player C# 3 Answers
Guided missile help c# 1 Answer
Issue's With Positioning 0 Answers