- Home /
Question by
Spardom · May 06, 2018 at 03:02 AM ·
2dmovementprogrammingcollision2d
when my 2d player hits a wall or any other collider they stop but if u keep trying you get pushed through
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
Direction currentDir;
Vector2 input;
private Rigidbody2D myRidgedbody;
bool isMoving;
Vector3 startPos;
Vector3 endPos;
float time;
public float walkSpeed = 3f;
public bool canMove;
void Start()
{
canMove = true;
myRidgedbody = GetComponent<Rigidbody2D>();
}
public IEnumerator Move(Transform entity)
{
isMoving = true;
startPos = entity.position;
time = 0;
endPos = new Vector3(startPos.x + System.Math.Sign(input.x),startPos.y + System.Math.Sign(input.y),startPos.z);
while(time < 1f)
{
time += Time.deltaTime * walkSpeed;
entity.position = Vector3.Lerp(startPos, endPos, time);
yield return null;
}
isMoving = false;
yield return 0;
}
void FixedUpdate()
{
}
// Update is called once per frame
void Update () {
if(!isMoving && canMove)
{
input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
if (Mathf.Abs(input.x) > Mathf.Abs (input.y))
input.y = 0;
else input.x = 0;
if (input != Vector2.zero)
{
StartCoroutine(Move(transform));
}
}
}
}
enum Direction
{
Up,left,down,right
}
This is the script i use to move the player collision does work with it but like i said u can still go through the walls
Comment
Answer by TreyH · May 06, 2018 at 03:06 AM
I imagine you just need to sync your movement with the physics cycle:
public IEnumerator Move(Transform entity)
{
var yieldInstruction = new WaitForFixedUpdate();
isMoving = true;
startPos = entity.position;
time = 0;
endPos = new Vector3(startPos.x + System.Math.Sign(input.x),startPos.y + System.Math.Sign(input.y),startPos.z);
while(time < 1f)
{
time += Time.fixedDeltaTime * walkSpeed;
entity.position = Vector3.Lerp(startPos, endPos, time);
yield return yieldInstruction;
}
isMoving = false;
yield return yieldInstruction;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Player movement script for a stickman 1 Answer
2D tile based game-engine 0 Answers
Why does my physics2D script cause the player to randomly stop moving? 0 Answers
PlayOneShot not playing sound 1 Answer