Hello everyone,
I’m working on a 2D tile based game with pokemon-like movement and so I need to prevent my character to pass trought walls. I’ve tried to do it with collision.
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);
}
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 OnTrggerEnter2D(Collider2D coll){
if (coll.gameObject.tag == "Wall")
{
transform.position = lastpos;
pos = lastpos;
Debug.Log ("Collision");
}
}
}
But my character went back to the lastpos before reaching the tile next to the wall.
I heard that I need to make an Array and to set up tile but I don’t know how to do it. I need to set the Array in a new script but how do I can get Array informations in my movement script?
If you can help me it will be really useful for continue my project indeed I’m looking on the web for 2 weeks and I don’t have answers. If I can’t do it I think I will give up my project.
Tanks
PS: Sorry for misspellings I’m French