How to make 2d character stop moving after collision with a box collider?
I am trying to make an RPG style game (much like Pokemon) for a school competition. I am currently trying to get the movement down to work perfectly but I am facing a problem with box colliders. My character and sprite which I am using to test the box collision will rotate when contact is made. I have tried freezing position both on the x and y and freeze position on z (not that it will do much). I am trying to get the character to stop moving when it collides with a box collider. I do not know how to fix this i have tried several things any help would be great. Here is the code I am using for my characters movement. It is not my original code.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour {
Direction currentDir;
Vector2 input;
bool isMoving = false;
Vector3 startPos;
Vector3 endPos;
float t;
public Sprite northSprite;
public Sprite eastSprite;
public Sprite southSprite;
public Sprite westSprite;
public float walkSpeed = 3f;
public bool isAllowedToMove = true;
void Start()
{
isAllowedToMove = true;
}
void Update () {
if(!isMoving && isAllowedToMove)
{
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)
{
if(input.x < 0)
{
currentDir = Direction.West;
}
if(input.x > 0)
{
currentDir = Direction.East;
}
if(input.y < 0)
{
currentDir = Direction.South;
}
if (input.y > 0)
{
currentDir = Direction.North;
}
switch(currentDir)
{
case Direction.North:
gameObject.GetComponent<SpriteRenderer>().sprite = northSprite;
break;
case Direction.East:
gameObject.GetComponent<SpriteRenderer>().sprite = eastSprite;
break;
case Direction.South:
gameObject.GetComponent<SpriteRenderer>().sprite = southSprite;
break;
case Direction.West:
gameObject.GetComponent<SpriteRenderer>().sprite = westSprite;
break;
}
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
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612151055im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How in move make Y=1 everytime ? 1 Answer
How do I use the capsule Collider? 1 Answer
How to deadtivate a gameobjects from the scene, if player has a character controller 0 Answers
Help with OnTriggerEnter Not working correctly? 1 Answer
Unity physics Help Implementing Real Life Physics in Jumping System C# 2 Answers