Hi guys, I have a 2D game where I need grid-based movement behavior. I have written this code, and it seem to work just fine when I used transform.position. However that didn’t register collisions, so I tried rigidbody2d.MovePosition, that resulted in a continuous movement and was not what I wanted. So I scraped that and decided to lerp the rigidbody position, problem is that it just sometimws works and sometimes it doesn’t. The code executes till the end without errors but the behavior says otherwise. Here’s the code.
public class Tile : MonoBehaviour
{
public float itemScore;
public float smooth = 2;
private bool moving = false;
void FixedUpdate()
{
Control ();
}
void Control ()
{
//If the tile isn't moving, take the player input and store it in a 2D vector. If that vector
//is not zero, start the movement coroutine.
if(!moving)
{
Vector2 input = new Vector2 (Input.GetAxisRaw("Horizontal"),Input.GetAxisRaw("Vertical"));
if (Mathf.Abs(input.x) > Mathf.Abs(input.y))
{
input.y = 0;
} else
{
input.x = 0;
}
if(input != Vector2.zero)
{
StartCoroutine(Move (input));
}
}
}
private IEnumerator Move (Vector2 input)
{
float t = 0;
moving = true;
Vector2 startPos = rigidbody2D.position;
Vector2 targetDelta = new Vector2 (input.x * GameController.GM.distanceDelta,input.y * GameController.GM.distanceDelta);
Vector2 targetPos = startPos + targetDelta;
while(rigidbody2D.position != targetPos)
{
t += Time.deltaTime * smooth;
rigidbody2D.position = Vector2.Lerp(startPos,targetPos,t);
yield return null;
}
moving = false;
yield return null;
}
So any tips?
isnt movetowards the same as lerp? Difference is that movetowards is limiting the speed. Also you can't call vector2 functions on a transform.position since its of vector3 type. I can't get it to work but I think that even if I did this would not register collisions.
– Kensei