This might come off as a stupid question, but in an if statement, is it possible to check if the object is currently colliding with another object?
Here is what I had thought of initially (in the code snipit bellow) but for some odd reason that I can't figure out, the variable onFloor is sometimes false when the object is being pushed upwards by the Platform.
void OnCollisionEnter2D(Collision2D c)
{
switch(c.gameObject.tag)
{
case "Platform":
onFloor = true;
break;
default:
break;
}
}
void OnCollisionExit2D(Collision2D c)
{
switch(c.gameObject.tag)
{
case "Platform":
onFloor = false;
break;
default:
break;
}
}
And for that reason, I am asking if there are any ways to detect if the circle collider of said object is colliding with box collider of intersecting object while in code.
something like
if(CircleCollider2D.CollidingObject != null && CircleCollider2D.CollidingObject.tag == "Platform")
{ /*Code I'd like to do here*/ }
Now that's only my imagination trying to think of some way of it that could work but you get the point.
So, I ask, are there any solutions for my imagination?
After discussing with Programmer, IsTouching is underlined and giving the error: 'Collider2D' does not contain a definition for 'IsTouching' and no extension method 'IsTouching' accepting a first argument of type 'Collider2D' could be found (are you missing a using directive or an assembly reference?).
Here is the slimmed down code:
using UnityEngine;
public class Ball : MonoBehaviour
{
Vector2 jumpVelocity;
public Collision2D platform;
// Use this for initialization
void Start()
{
jumpVelocity = new Vector2(0, rigidbody2D.gravityScale * 100);
}
void FixedUpdate()
{
if (Input.GetKey(KeyCode.Space) && collider2D.IsTouching(platform))
{
rigidbody2D.AddForce(jumpVelocity, ForceMode2D.Force);
}
}
}
note that even changing collider2D to a Collision2D variable and taking that variable.collider.IsTouching results the same error.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…