Player Movement - Not moving at all
Hello everyone
I realise something like this was asked a million times although I did not find anything similar to my code ad problem.
I am fairly new to Unity, so I am sorry if there are some things that are redundant or misplaced on the code.
I have a script to move my character(player) The script should be fine and it does not have any errors, although when I press play I try to use the arrows and it does not work and I don't know why.
Here is the code. I appreciate any help you can give me, thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Direction currentDir;
Vector2 input;
bool isMoving = false;
Vector3 startPos;
Vector3 endPos;
float t;
public float walkSpeed = 3f;
// Update is called once per frame
void Update()
{
if (isMoving)
{
input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (Mathf.Abs(input.x) > input.y)
input.y = 0;
else
input.x = 0;
if (input != Vector2.zero)
{
StartCoroutine(Move(transform));
}
}
}
public IEnumerator Move(Transform entity)
{
isMoving = true;
startPos = entity.position;
t = 0;
endPos = new Vector3(startPos.x + System.Math.Sign(input.x), startPos.y +
System.Math.Sign(input.y), startPos.z);
while (t < 1f)
{
t += Time.deltaTime * walkSpeed;
entity.position = Vector3.Lerp(startPos, endPos, t);
yield return null;
}
isMoving = false;
yield return 0;
}
enum Direction
{
North,
East,
South,
West
}
}
Answer by Bilelmnasser · Apr 13, 2017 at 09:44 AM
isMoving is always false in your script, nothing will ever happen !!
Answer by andycodes · Apr 13, 2017 at 06:33 AM
Your Main problem is that isMoving is set to False when you declare it, so when Update() calls,
if(isMoving)
always returns false, therefore the rest of your code within that statement will never get called.
Since its a private variable I assume you aren't calling it elsewhere, so the only information i can gather to give you is to implement this:
void Start(){
isMoving = true;
}
Answer by ECGBastos · Apr 13, 2017 at 02:54 PM
Oh yeah, got it!
One problem though. When I click any of the arrows, my characters (sprite) disappears...