Question by
Ddaron · Oct 20, 2015 at 09:32 PM ·
collisionjumpcollider2dplatformerplatform
Collider2D of game object does not work, unless I duplicate the game object.
I am trying to implement one way platforms in my "game", I am doing it like this:
public class OneWayPlatform : MonoBehaviour {
public Transform player;
private Collider2D collider;
private float halfTheSpriteSize;
private float halfThePlayerSize;
public bool isPlayerAbove;
void Start()
{
collider = GetComponent<Collider2D>();
halfTheSpriteSize = collider.gameObject.GetComponent<SpriteRenderer>().bounds.size.y / 2;
halfThePlayerSize = player.gameObject.GetComponent<Collider2D>().bounds.size.y / 2;
if (player == null)
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
}
// Update is called once per frame
void FixedUpdate () {
Debug.DrawLine(new Vector3(player.position.x, player.position.y - halfThePlayerSize, 0),
new Vector3(collider.gameObject.transform.position.x, collider.gameObject.transform.position.y + halfTheSpriteSize, 0), Color.red);
this.isPlayerAbove = ((collider.gameObject.transform.position.y + halfTheSpriteSize) - (player.position.y - halfThePlayerSize)) < 0;
if (isPlayerAbove)
{
collider.enabled = true;
}
else
{
collider.enabled = false;
}
}
}
This solution does not work... UNLESS I copy the platform and move it over, then it works perfectly, sometimes...
Is this way of thinking good at all? Is calculating distance on y axis a good solution to make one way platforms?
Comment
Best Answer
Answer by Ddaron · Oct 21, 2015 at 05:31 AM
I fixed the issue. The key was here:
this.isPlayerAbove = ((collider.gameObject.transform.position.y + halfTheSpriteSize) - (player.position.y - halfThePlayerSize)) < 0;
Due to incosistent sizes of sprites and colliders in my scene (this is a prototype), even though I thought it should be zero, it was not. To correct this issue I used:
this.isPlayerAbove = ((collider.gameObject.transform.position.y + halfTheSpriteSize) - (player.position.y - halfThePlayerSize)) <= 0.1f;
The solution might not be optimal, but Im staying with the KISS rule for my prototype - and learning example.