- Home /
Need help moving an object 1 step at a time (c#)
I am making a 2d game and I need the player to move on a grid. I currently have it so I can give a direction and it will keep moving one step per frame but that is too fast. I want it to move more like one step a second. I have tried using yield return WaitForSecond(x); in a coroutine but its not working. Please help and thanks for your time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private float speed;
public float axisX;
public float axisY;
public Vector3 pos;
// Use this for initialization
void Start()
{
speed = 3;
}
// Update is called once per frame
void Update()
{
Vertical();
Horizontal();
//transform.Translate(new Vector3(axisX, axisY) * Time.deltaTime * speed);
move();
StartCoroutine(waiter());
}
float Vertical()
{
if (Input.GetKeyDown(KeyCode.DownArrow))
{
axisY = -1;
axisX = 0;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
axisY = 1;
axisX = 0;
}
return axisY;
}
float Horizontal()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
axisX = -1;
axisY = 0;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
axisX = 1;
axisY = 0;
}
return axisX;
}
public void move()
{
pos = transform.position;
pos.x += axisX;
pos.y += axisY;
transform.position = pos;
}
IEnumerator waiter()
{
yield return new WaitForSeconds(4);
}
}
Answer by tormentoarmagedoom · Jun 26, 2018 at 03:20 PM
Good day.
You can create a Cooldown, of 1 secondto control the movement.
Is very simple, you only need something like this:
float TotalCooldown = 1;
float ActualCooldown = 1;
bool OnCooldown = true;
void Update()
{
if (ActualCooldown > 0)
{
OnCooldown = true;
ActualCooldown-= Time.deltaTime;
}
else if (ActualCooldown <= 0)
{
OnCooldown=false;
}
if (OnColldown==false)
{
ActualCooldown=TotalCooldown;
MovethePlayer();
}
}
ITs very simple! The player will execute the method MoveThePlayer only 1 every second. And you can modify the TotalCooldown to control time between movemnt.
Bye! :D
worked, yay <3 I put it into a function that returns OnCoolDown to make it easier to use in multiple places.
Answer by $$anonymous$$ · Jun 29, 2018 at 05:17 AM
hello, guys, I'm going to show you how to fix audio problems no any problems within Windows 10 operating system If you also have problems with audio, then this website is for you. If you have any problems relating to the window then you can visit this website
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Add audio. 1 Answer
Making 2d joystick correct to controls (mobile) 0 Answers
Animator - Wait until animation finishes 3 Answers