Я пытался сделать эту работу некоторое время, и я терплю неудачу.
У меня есть Rigidbody2D на 2D-уровне сверху вниз, и я пытаюсь просто переместить его по координатам (уровни похожи на сетку), поэтому одно нажатие кнопки/шага равно ровно одному пройденному квадрату. Должна быть возможность идти только в одном из четырех направлений, и независимо от того, когда пользователь останавливает движение ходьбы, оно должно заканчиваться квадратом. Хороший игровой эквивалент того, чего я хочу добиться, это луфия/дыхание огня/любая подобная серия РПГ. Я пытался использовать сопрограммы, чтобы заставить функцию обновления ждать одну секунду после каждого шага, но это, похоже, не работает. Самое близкое, к чему я пришел, это код ниже. Спасибо, парни!
public class PlayerMovement2D : MonoBehaviour
{
Rigidbody2D rbody;
Animator anim;
float speed = 1.25f;
Vector2 pos;
void Start()
{
rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
pos = rbody.position;
}
void FixedUpdate()
{
Vector2 movement_vector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (movement_vector.x != 0 || movement_vector.y != 0)
{
if (movement_vector.x > 0)
{
pos += Vector2.right;
pos.y = 0;
}
else if (movement_vector.x < 0)
{
pos += Vector2.left;
pos.y = 0;
}
else if (movement_vector.y > 0)
{
pos += Vector2.up;
pos.x = 0;
}
else if (movement_vector.y < 0)
{
pos += Vector2.down;
pos.x = 0;
}
anim.SetBool("IsWalking", true);
anim.SetFloat("Input_x", movement_vector.x);
anim.SetFloat("Input_y", movement_vector.y);
}
else
{
anim.SetBool("IsWalking", false);
}
rbody.position = Vector2.MoveTowards(rbody.position, pos, speed * Time.deltaTime);
//transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
pos = rbody.position;
}
}