How to move a character along the Y axis x amount of units using the G key?
Hey guys, I am decently new to coding, so I am not sure what I am doing wrong but im trying my best to get this to work. Any help is appreciated. What I am trying to do, is move my player character up the y axis a good amount of units when pressing the "G" button on the keyboard, effectively "Teleporting" my character. This is my coding so far, sorry for the lengthy explanation
using UnityEngine;
using System.Collections;
public class Teleportation : MonoBehaviour {
// Use this for initialization
private void Start () {
GameObject player = GameObject.Find ("Player");
if (Input.GetKey(KeyCode.G){
transform.playerpos= new Vector3(0,0,0);
}
}
}
Answer by Salmjak · Jul 24, 2016 at 08:31 PM
GameObject player;
void Start () {
player = GameObject.Find ("Player");
}
float JumpOffset = 5f;
void Update(){
if (Input.GetKey(KeyCode.G){
player.transform.position = new Vector3(player.transform.position.x,player.transform.position.y+JumpOffset,player.transform.position.z);
}
}
Any input-detection should be in a repeating function (usually Update()) so that it can be detected. Then you want to use the transform of the gameobject (player.transform, where player is your gameobject) and set it to a new Vector3 were every variable is your current position with an offset to create a new position that is above the gameobject.
Thanks man that's exactly what I was looking for. I was wayyyy off. Part of the learning process I suppose though. If you would be so kind as to indulge me a bit further, if I changed the key, and then changed the JumpOffset to -5, should that button then return me to my original position?
Also, is there an easy method to end this cycle? I noticed I can hold g and it keeps me up.
@ridgedtip Changing the jumpoffset (or creating another variable for the new purpose) would do that yes. But only if you do not have any gravity or other forces acting on the gameobject. You could save the old position in a Vector3 if you want to return to the exact same position! Or you could just save the old Y-position! :)
There is a way to ter$$anonymous$$ate the cycle. Input.Get$$anonymous$$ey is true every frame you're holding down the key. If you only want it to be true when pressing you should use Input.Get$$anonymous$$eyDown which is only true once, and that is when you press the key down.
If you want some kind of cooldown you should look into using a boolean together with a Coroutine and WaitForSeconds().
Your answer
Follow this Question
Related Questions
VR Teleporting on any object 0 Answers
SteamVR Interaction system. Small problem with Teleport points. 3 Answers
Can't make player character teleport from one side of screen to another. 1 Answer
Teleporting script won't work,Whats wrong with my teleporting script 0 Answers
is there a way to teleport the player to a certain coordinate right after loading a scene? 0 Answers