- Home /
2D Tile Based collision problem
Okay, so basically I'm trying to make a game similar to the early Ultima's (I-V) I tried to implement a basic code I found on the forums and it works Perfectly! except for one big problem; collisions aren't being detected on the -x and +y planes (Left and Up?) and the collision boxes for the player and the walls seem to get stuck in each other; rendering my player completely stuck, with restarting being the only solution: I've tried plenty of fixes such as changing the material of the wall colliders to set the friction to 0, or using an edge collider instead of a boxcollider2d but none of these have worked; help is greatly appreciated. My Code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class Movementy : MonoBehaviour
{
public float speed = 2.0f;
Vector3 pos;
Vector3 old;
Transform tr;
void Start()
{
pos = transform.position;
tr = transform;
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.UpArrow) && tr.position == pos)
{
pos += (Vector3.up) / 1;
}
else if (Input.GetKey(KeyCode.RightArrow) && tr.position == pos)
{
pos += (Vector3.right) / 1;
}
else if (Input.GetKey(KeyCode.DownArrow) && tr.position == pos)
{
pos += (Vector3.down) / 1;
}
else if (Input.GetKey(KeyCode.LeftArrow) && tr.position == pos)
{
pos += (Vector3.left) / 1;
}
transform.position = Vector3.MoveTowards(transform.position, pos, Time.deltaTime * speed);
}
void OnCollisionEnter2D()
{
float x = transform.position.x;
float y = transform.position.y;
float z = transform.position.z;
if ((int)(x + 0.5) > (int)x && x > 0)
x = (int)x + 0.5f;
else if ((int)(x - 0.5) < (int)x && x < 0)
x = (int)x - 0.5f;
else
x = (int)x;
if ((int)(y + 0.5) > (int)y && y > 0)
y = (int)y + 0.5f;
else if ((int)(y - 0.5) < (int)y && y < 0)
y = (int)y - 0.5f;
else
y = (int)y;
z = 0f;
Vector3 away = new Vector3(x, y, z);
pos = away;
}
}
The code is pretty simple. Should be really easy to use Debug.Log to print out the values and see which if-branch you end up in which case.
At least keep in $$anonymous$$d that
(int)0.6f + 0.5f; // result it 0.5 float
(int)(0.6f + 0.5f) // result 1 int
Hello, after adding the following lines of code to the script I get these messages in the console, I believe the problem to lie in the script only accepting movement on a positive or negative direction. A fix for this would be greatly appreciated
Thanks for replying!
Part of the problem is in the OnCollisionEnter2D:
x + 0.5f > x
Will always return true so there is no need to check for that. Same goes for 'x - 0.5f < x'. I tried my hardest to reproduce this bug, but alas, I could not get OnCollisionEnter2D() to fire...
$$anonymous$$y suggestion to make things simpler would be for you to try to use a CharacterController Component, as it has build in collision detection built into its move functions.... IIRC. Sorry I couldn't offer anymore help. Good luck!