How to detect collision between moving rigidbody cube and static empty object? - unity3d

I am new to unity and working on collision detection.
I have a rigidbody cube and an empty object with a cube mesh. The rigidbody cube moves with arrow keys and the empty object is static. Both have a box collider.
How do I detect collision between this empty object and the rigidbody cube?
I am wondering whether it should be OnCollisionEnter or OnTriggerEnter and how to use the correct command.
Thank you for your help.

First you need to set the box collider component to the cube and to the empty object with cube mesh. Then you can use this code:
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public PlayerMovement movement;
public GAME_MANAGER GameManager;
private void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false;
}
}
}
Make sure you have set the tag of the obstacle to “Obstacle” and add this script to the player or the cube. Here,
movement.enabled = false;
You can apply you own logic according to your need.
Thanks

Related

Destroy gameobject in Unity

I want the enemy to be destroyed when the player touches the heart. what's wrong with my code?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemy : MonoBehaviour
{
public GameObject player;
public float speed;
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, player.transform.position,
speed * Time.deltaTime);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (player.gameObject.CompareTag("haret"))
{
Destroy(gameObject);
}
}
}
You haven't provided an error code or anything so I don't have much to go off of ;-;
make sure the tag in the code is the same as the code in the project and put the tag on the heart.
make sure that the player gameobject has been assigned to the enemy.
make sure that the player and the heart both have a 2d collider not set to is trigger
Check your tag spelling. You have a spelling mistake there.
Without an error it is hard to figure out what the problem is. From the looks of it you might have misspelled gameObject.CompareTag("haret") where it should be gameObject.CompareTag("heart") instead.
Also make sure that the script is assigned to the enemy, that you have assigned the player gameObject in the inspector and that you have set the collider of the heart gameObject to isTrigger in the inspector.

How do you switch scenes in Unity 2D on collison

I was wondering how I can switch scenes in my 2D Unity game. I put the scenes in the build and the objects are entering in colison. I used this code but it didn't worked:
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneSwitch : MonoBehaviour
{
[SerializeField] private string WhatScene;
void OnTriggerEnter(Collider2D other)
{
if (other.CompareTag("Player"))
{
SceneManager.LoadScene(WhatScene);
}
}
}
Can you help me?
https://i.stack.imgur.com/rpg3t.png
https://i.stack.imgur.com/HoOfl.png
https://i.stack.imgur.com/9GEgi.png
Note that there is
OnTriggerEnter2D(Collider2D) which as parameter takes a Collider2D, not Collider. This one is for 2D physics using Rigidbody2D and Collider2D components.
OnTriggerEnter(Collider) which takes a Collider, **not Collider2D. This one is for 3D physics using Rigidbody and Collider components.
Since you are talking about 2D your method should look like
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
SceneManager.LoadScene(WhatScene);
}
}
If you are using OnTriggerEnter method in unity2D there is a problem, you need to set collision as a trigger and use "OnTriggerEnter2D" method.
In build settings you have to add scenes, there will be a different index attributed to every scenes.
private void OnTriggerEnter2D(Collider other)
{
if (other.CompareTag("TAG"))
{
SceneManager.LoadScene([INDEX OF THE SCENE YOU WANT TO USE]);
}
}
If you want to detect a collision use OnCollisionEnter2D.

Unity collision not detected

I'm making a Unity game, in which player should push all "Enemy" object from the plane. So to be able to count the number of fallen objects I want to generally be able to tell when a collision occurred between the red cube and every other cube. The script seems to not detect a collision, how to fix it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collide : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Enemy")
Destroy(gameObject);
Debug.Log("Hit Occured");
}
}
you need OnCollisionEnter
void OnCollisionEnter(Collision collision){
}
because your colliders aren't triggers.
You need to implement OnCollisionEnter(Collision collision) not OnTriggerEnter(Collider other) or check BoxCollider IsTrigger checkbox
There are 3 things to be checked
1. The OnCollisionEnter should be used in place of OnTriggerEnter
2. isTrigger checkbox should be enabled so that the event is triggered when the both bodies collide with other .
3. The most important thing which no one has mentioned is the tags given to the gameobject or the enemies because we need to define the gameobject that event should be triggered when hit to the specific body because the gameobject contains the collider and can collide to any wall or something so you need to define the tags properly

Collision callback function not called

i am bloody beginner with Unity and i am currently working on a 2D Brawler. The movement works perfectly but my colliders don't do what they should... I want to detect if two GameObjects Collide (Spear and Player2) and if the collide Player2s healthPoints should decrease by Spears AttackDamage.
The names of the GameObjects are also their tags. The Spears Prefab has following configuration: SpriteRendered(Material Sprites-Default), BoxCollider2D(Material None Physics Material 2D, IsTrigger(not activated), UsedByEffector(also not activated) Rigidbody2D(Kinematic, None Material, Simulated(Activated), KinematicContacts(activated), Standard configs for the rest))
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpearCtr : MonoBehaviour {
public Vector2 speed;
public float delay;
Rigidbody2D rb;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = speed;
Destroy(gameObject, delay);
}
void Update ()
{
rb.velocity = speed;
}
}
The Players Configurations
The Spears Configurations
This was the code i have tried before
OnCollision2D(Collision2D target);
{
if (target.gameObject.tag == "Spear")
{
hp = -1;
if (hp <= 0)
{
alive = false;
}
}
}
I hope someone can tell me how to get this working
Thanks for all the answers
(BTW sorry for my bad english I am austrian)
enter image description here
enter image description here
Reasons why OnCollisionEnter() does not work:
Collison:
1.Rigidbody or Rigidbody2D is not attached.
At-least, one of the two GameObjects must have Rigidbody attached to it if it is a 3D GameObject. Rigidbody2D should be attached if it is a 2D GameObject/2D Collider.
2.Incorrect Spelling
You failed to spell it right. Its spelling is also case sensitive.
The correct Spellings:
For 3D MeshRenderer/Collider:
OnCollisionEnter
OnCollisionStay
OnCollisionExit
For 2D SpriteRenderer/Collider2D:
OnCollisionEnter2D
OnCollisionStay2D
OnCollisionExit2D
3.Collider has IsTrigger checked. Uncheck this for the OnCollisionXXX functions to be called.
4.The script is not attached to any of the Colliding GameObjects. Attach the script to the GameObject.
5.You provided the wrong parameter to the callback functions.
For 3D MeshRenderer/Collider:
The parameter is Collision not Collider.
It is:
void OnCollisionEnter(Collision collision) {}
not
void OnCollisionEnter(Collider collision) {}
For 2D SpriteRenderer/Collider2D:
6.Both Rigidbody that collides has a isKinematic enabled. The callback function will not be called in this case.
This is the complete collison table:

Google Cardboard - How to detect focus on an object?

I try to create a VR scene in unity using google cardboard sdk. I add a cube and CardboardMain.prefab to scene. There is an example scene that detect focus on cube. Its hierarchy view is :
I don't know how to add GUIReticle object or prefab like as the image.
How can I detect focus on an object?
Actually you could make the script by your own and it is quite simple.
You could detect whether the user is looking at your object or not by using RayCast from the Main Camera. If the RayCast hit your object, then it is being focused on.
For example:
using UnityEngine;
using System;
[RequireComponent(typeof(Collider))]
public class LookableObject : MonoBehaviour {
[SerializeField]
Transform cam; // This is the main camera.
// You can alternately use Camera.main if you've tagged it as MainCamera
bool focus; // True if focused
Collider gazeArea; // Your object's collider
public void Start () {
gazeArea = GetComponent<Collider> ();
}
public void Update () {
RaycastHit hit;
if (Physics.Raycast (cam.position, cam.forward, out hit, 1000f)) {
focus = (hit.collider == gazeArea);
} else {
focus = false;
}
}
}
Edit: This is just an example. You probably would want to make a script to do the Raycast only just once instead of doing the Raycast on each of your object over and over again to make your project runs faster.