[Unity2D] Collision bug
If I ask today your help is because after hours of$ research on the internet I did not find the answer to my problem:
have a grid movement system(pokemon-like) and when I collide with a wall I put my character back on the square where it was before the collision. The problem is that the collision is done before the character is on the square. So I can not move on a square juxtaposed to a wall.
Here is my code (C #):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Deplacement : MonoBehaviour
{
Animator anim;
Vector3 pos; // For movement
Vector3 lastpos;
float speed = 2.0f; // Speed of movement
Vector3 localscale;
GameObject perso;
void Start()
{
pos = transform.position; // Take the initial position
perso = GameObject.Find("Perso_sprite");
anim = perso.GetComponent<Animator>();
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Q) && transform.position == pos)
{ // Left
lastpos = pos;
pos += Vector3.left;
anim.SetBool ("Up", false);
anim.SetBool ("Down", false);
anim.SetBool ("Right", false);
anim.SetBool ("Left", true);
anim.SetBool ("Pause", false);
anim.SetBool ("Walk", true);
}
if (Input.GetKey(KeyCode.D) && transform.position == pos)
{ // Right
lastpos = pos;
pos += Vector3.right;
anim.SetBool ("Up", false);
anim.SetBool ("Down", false);
anim.SetBool ("Right", true);
anim.SetBool ("Left", false);
anim.SetBool ("Pause", false);
}
if (Input.GetKey(KeyCode.Z) && transform.position == pos)
{ // Up
lastpos = pos;
pos += Vector3.up;
anim.SetBool ("Up", true);
anim.SetBool ("Down", false);
anim.SetBool ("Right", false);
anim.SetBool ("Left", false);
anim.SetBool ("Pause", false);
}
if (Input.GetKey (KeyCode.S) && transform.position == pos) { // Down
lastpos = pos;
pos += Vector3.down;
anim.SetBool ("Up", false);
anim.SetBool ("Down", true);
anim.SetBool ("Right", false);
anim.SetBool ("Left", false);
anim.SetBool ("Pause", false);
}
transform.position = Vector3.MoveTowards (transform.position, pos, Time.deltaTime * speed);// Move there
if(pos == transform.position ){
anim.SetBool ("Pause", true);
}
}
void OnTriggerEnter2D(Collider2D coll){
if (coll.gameObject.tag == "Wall")
{
transform.position = lastpos;
pos = lastpos;
Debug.Log ("Collision");
}
}
}
The box collider off the wall make exactly the size of a square of the grid, and IsTrigger is activated.
The box collider of the wall is exactly the size of a box and it has the function IsTrigger of activated. If I reduce the size of the collider of my character or the wall, my character passes through the wall.
In front of the wall (collider reduced)
When the character go trought the wall
Sorry for the English, I'm french and I'm doing my best.