Question by
shrimpslayer · May 05, 2021 at 09:42 PM ·
2dcollisionmovementcollision detection
How would I implement collisions with my tile-based movement?
Absolute beginner here (just created my project a couple hours ago and have no idea how to program), i followed a tutorial for a tile based movement system and it works fine, although i need hep with calculating collisions.
It seems to check and update only when my player isn't moving, after which it snaps it back to its position before it started clipping. I'm calculating my collisions just with physics and rigidbody components.
How would i do collisions based on physics rather than movement? Would I even have to do that? Please give help.
public class movement : MonoBehaviour
{
private float timeToMove = 0.25f;
public float walkSpeed = 0.25f;
public float sprintSpeed = 0.15f;
private bool isMoving;
private Vector3 origPos, targetPos;
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W) && !isMoving)
StartCoroutine(MovePlayer(Vector3.up));
if (Input.GetKey(KeyCode.A) && !isMoving)
StartCoroutine(MovePlayer(Vector3.left));
if (Input.GetKey(KeyCode.S) && !isMoving)
StartCoroutine(MovePlayer(Vector3.down));
if (Input.GetKey(KeyCode.D) && !isMoving)
StartCoroutine(MovePlayer(Vector3.right));
if (Input.GetKey(KeyCode.LeftShift))
timeToMove = sprintSpeed;
else timeToMove = walkSpeed;
}
private IEnumerator MovePlayer(Vector3 direction)
{
isMoving = true;
float elapsedTime = 0;
origPos = transform.position;
targetPos = origPos + direction;
while(elapsedTime < timeToMove)
{
transform.position = Vector3.Lerp(origPos, targetPos, (elapsedTime / timeToMove));
elapsedTime += Time.deltaTime;
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}
Comment