- Home /
I have no idea how to check if two 2D objects are colliding
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ballMovement : MonoBehaviour {
public GameObject bowlingBallObj;
public GameObject foregroundObj;
public float leftForce = -50f;
public float rightForce = 50f;
public float upForce = 2000f;
private bool isDead = false;
private Rigidbody2D rb2d;
CircleCollider2D bowlingBall = bowlingBallObj;
BoxCollider2D ground = foregroundObj;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
bowlingBallObj = GameObject.Find("Bowling Ball");
foregroundObj = GameObject.Find("Foreground");
}
// Update is called once per frame
void Update () {
if (isDead == false)
{
if (Input.GetKey(KeyCode.A))
{
rb2d.AddForce(new Vector2(leftForce, 0));
}
if (Input.GetKey(KeyCode.D))
{
rb2d.AddForce(new Vector2(rightForce, 0));
}
if(bowlingBall.IsTouching(ground))
{
if (Input.GetKeyDown(KeyCode.Space))
{
rb2d.AddForce(new Vector2(0, upForce));
}
}
}
}
} I am just trying to make a simple program where a bowling ball can roll and jump around once. I want it so the bowling ball can't jump twice and can only jump while touching the ground.
Answer by adipatil3517 · Oct 23, 2017 at 04:47 AM
write function OnCollisionEnter2D(collider other) { Debug.Log("Colliding"); } if two objects are colliding you will get to know about it
Answer by Tony_2015 · Oct 23, 2017 at 06:22 AM
A better way of doing it would be using Physics.checkSphere. Hope this helps.
//Make bool like say Grounded Public bool Grounded;
//this is the position where the object will check for ground
Public GameObject GroundChecker;
//this is your ground. Put your ground object on a new layer called ground and then select the ground layer in the script
Public LayerMask Ground;
Void Update() {
Grounded = Physics.CheckSphere(GroundChecker.transform.position,0.05f,Ground);
If(Grounded) { (Input.GetKeyDown(KeyCode.Space)) { rb2d.AddForce(new Vector2(0, upForce)); } } }
Your answer
Follow this Question
Related Questions
How to make particles collide with something but at the same time phase through it 2 Answers
How do I fix this weird collision "bug"? 1 Answer
use OnParticleCollision(GameObject)for AOE spell/magic creation problem 1 Answer
How to detect different parts in sprite? 2 Answers
Why is the material switching back after collision? 1 Answer