- Home /
Move player step by step
Hi im trying to move my player in WASD direction; when I press W i want that my player moves only for example 1 second or 15u in X axes and then i have to press again W to move it.
using UnityEngine;
using System.Collections;
public class PlayerMove : MonoBehaviour {
public KeyCode moveUp;
public KeyCode moveDown;
public KeyCode moveLeft;
public KeyCode moveRight;
public float moveSpeed;
public Vector3 pointB;
public bool moving = false;
void Update()
{
if (Input.GetKey (moveUp)) {
pointB = (0,transform.position.y + 10,0);
moving = true;
}
if (Input.GetKey (moveDown)) {
pointB = (0,transform.position.y - 10,0);
moving = true;
}
if (Input.GetKey (moveLeft)) {
pointB = (transform.position.x-10,0,0);
moving = true;
}
if (Input.GetKey (moveRight)) {
pointB = (transform.position.x-10,0,0);
moving = true;
}
}
IEnumerator Start()
{
var pointA = transform.position;
while (moving == true) {
yield return StartCoroutine(MoveObject(transform, pointA, pointB, moveSpeed));
}
}
IEnumerator MoveObject(Transform thisTransform, Vector3 startPos, Vector3 endPos, float time)
{
var i= 0.0f;
var rate= 1.0f/time;
while (i < 1.0f) {
i += Time.deltaTime * rate;
thisTransform.position = Vector3.Lerp (startPos, endPos, i);
yield return null;
if (transform.position == pointB)
{
moving = false;
}
}
}
}
But when I press any key doesn't works
Comment
Your answer

Follow this Question
Related Questions
Player can't move in windows standalone 2 Answers
Rythm Game - Move objects synchronized with the music 1 Answer
FBX models move along with the fps character when played 0 Answers
Google VR Play Store sample app built using Unity 3D with move and rotate 1 Answer
triangles at the corner of canvas panels not showing. what do I do ? 1 Answer