OnTriggerEnter not firing when character enters - c#

I am new to unity. I am trying to make a character walk into a spinning gold coin and collect it.
I have a character downloaded from mixamo named 'brute'. in CoinScript.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinScript : MonoBehaviour {
// Use this for initialization
void Start(){
}
// update is called once per frame
void Update(){
transform.Rotate(0, 0, 90 * Time.deltaTime);
}
private void OnTriggerEnter(Collider other){
GUI.Label (new Rect (10, 10, 100, 20), "name: " + other.name);
if (other.name == "brute") {
other.GetComponent<PlayerScript> ().points++;
// Add 1 to points
Destroy (gameObject); // this destroy things
}
}
}
PlayerScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerScript : MonoBehaviour {
public int points = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
private void onGUI(){
GUI.Label (new Rect (10, 10, 100, 20), "Score: " + points);
}
}
I added CoinScript to Coin which is a cylinder object. coin:
Transform
Clinder
Mesh Renderer
Box Collider
CoinScript
(I tried to add and remove RigidBody but, OnTriggerEnter did not fire)
and for brute
Transform
Animator
RigidBody
Character Controller
Box Collider
Capsule Collider
Player Script
Move Script
I want OnTriggerEnter to be triggered when brute walk into the coin. thanks for your help.

Here are the basic conditions for OnTriggerEnter to work correctly:
Both objects much have a collider, and one of them should have a rigid body and a collider. the other one may just be a collider.
One of colliders should have IsTrigger = true (set from the inspector). if both of them has IsTrigger = true it will not work.
If you dont want physics, you may use isKinematic = true on the Rigidbody.
In your case, you also happen to have Multiple colliders on the player's body. make sure they all/ the colliders of interest have isTrigger set to true. The coin, on the other hand can have a collider and a RigidBody with isKinematic = true, and the trigger events should work correctly.

One of the object must have the "Is trigger"-property checked. If one of your objects (e.g. the coin) is a trigger you can use the OnCollisionEnter function.
Read it: https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html

Related

My characters in my 2D game do not collide even when i create 2D collider box

i want to make the characters in my game collide with objects around them and stop moving. the thing is the characters just spawn and keep walking down the map until they're out of the Canvas view.
my characters have Constantmove script that i assigned to them which is this one:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterConstantMove : MonoBehaviour
{
GameManager Game_Manager;
void Start()
{
GameObject gameController = GameObject.FindGameObjectWithTag("GameController");
Game_Manager = gameController.GetComponent<GameManager>();
}
void Update()
{
transform.Translate(Game_Manager.moveVector * Game_Manager.moveSpeed * Time.deltaTime);
}
}
What do i do to make them stop around the desk and just stay idle when they collide there?
You are moving them with transform.Translate() function, which does not include physics. If you want them to collide, you would have to add Rigidbody2D component and move them using velocity property: https://docs.unity3d.com/ScriptReference/Rigidbody2D.html

Move Object Along Raycast

I have made a Raycast that goes from my camera to the point of the object clicked. However, I am trying to make an object (in this case a bullet) to fly along the path of the ray. At the moment it flies straight forwards from the camera no matter where on the object you click because of the vector 3. How would I get it to follow the Ray?
C#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RaycastShot : MonoBehaviour {
public Camera camera;
private Ray ray;
private RaycastHit hit;
public GameObject bullet;
private GameObject createBullet;
private Collider collider;
void Update () {
if (Input.GetMouseButtonDown (0)) {
ray = camera.ScreenPointToRay (Input.mousePosition);
createBullet = Instantiate (bullet, camera.transform.position, bullet.transform.rotation);
createBullet.AddComponent<Rigidbody>();
createBullet.GetComponent<Rigidbody>().AddRelativeForce (new Vector3(0, 1500, 0));
createBullet.GetComponent<Rigidbody>().useGravity = false;
collider = createBullet.GetComponent<Collider> ();
Destroy (collider);
if (Physics.Raycast (ray, out hit)) {
}
}
Debug.DrawLine (ray.origin, hit.point, Color.red);
}
}
You would want to use ray.direction property instead of (0,1500,0) as the direction of the force.
The add force should occur in FixedUpdate, and should only occur if the Ray hits something. Where you have it now is probably not the best spot.
Of course, make sure the bullet gets instantiated at the camera's location first.
Ray.direction gives you the vector3 direction of the ray object. If you need the distance at which it hit, you could also use ray.distance.
Edit: I'm near my computer now, so here's a more detailed answer relating to your comments.
First off: Here's the way I set up the test Project:
I Created a prefab bullet. This is just a sphere with a rigidbody, with my "BulletController" script attached to it. The point of prefabs is to avoid all of those lines where you have to add components. For testing purposes I set the rigibody to ignore gravity and its mass to 0.1.
Next, I created the BulletController script, which will be attached to the bullet prefab.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletController : MonoBehaviour {
Rigidbody rb;
public float bulletForce;
bool firstTime = false;
Vector3 direction;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
}
public void SetDirection (Vector3 dir) {
direction = dir;
firstTime = true;
}
void OnCollisionEnter () {
//code for when bullet hits something
}
void FixedUpdate () {
if (firstTime) {
rb.AddForce (direction * bulletForce);
firstTime = false;
}
}
}
This script is is charge of controlling bullets. The (later on) script that will create the bullets doesn't really care what happens to them afterwards, since its job is just to create bullets. This BulletController script is in charge of dealing with bullets once they're created.
The main parts are the SetDirection method which tells the bullet which direction to travel in. Also it adds a one-time force in its FixedUpdate method that pushes it in the direction you just set. FixedUpdate is used for physics changes like adding forces. Don't use Update to do this kind of thing. It multiplies the force by a force that you set called "bulletForce".
Finally the BulletListener Script, which is simply attached to an empty game object in the scene. This script is in charge of listening for mouse clicks and creating bullets towards them.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletListener : MonoBehaviour {
public Camera mainCamera;
public BulletController bulletPrefab;
void Update () {
if (Input.GetMouseButtonDown (0)) {
//create ray from camera to mousePosition
Ray ray = mainCamera.ScreenPointToRay (Input.mousePosition);
//Create bullet from the prefab
BulletController newBullet = Instantiate (bulletPrefab.gameObject).GetComponent<BulletController> ();
//Make the new bullet start at camera
newBullet.transform.position = mainCamera.transform.position;
//set bullet direction
newBullet.SetDirection (ray.direction);
}
}
}
In the inspector for this empty game object, I added this script, and then dragged the camera, and the bulletPrefab into the appropriate fields. Be sure to drag the prefab from the FOLDER, not from the SCENE. Since this will use the prefab, not an object in the scene.
Now click around and you'll see the bullets flying! Note that using a low force is good to test, and then increase it later.
The main things to take away from this is to split up your logic. A script should only be in charge of one thing. For example, your enemies might also fire bullets. You can now reuse your bulletController script for those bullets as well. Also, say you have different sized or shaped bullets, you can just drag the bulletcontroller script onto the different prefabs you've made for your bullets. This will not affect your listener script which will still create bullets where you click.
If you have the end point then you can move along the vector with MoveTowards:
Vector3 target = hit.point;
StartCoroutine(MoveAlong(target));
private IEnumerator MoveAlong(Vector3 target){
while(this.transform.position != target){
this.transform.position = MoveTowards(this.transform.position, target, step);
yield return null;
}
}

How can i rotate smooth the characters back on colliding?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxCollider : MonoBehaviour {
private float degree = 180f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider c)
{
GameObject character = GameObject.Find(c.name);
character.transform.rotation = Quaternion.Slerp(character.transform.rotation, Quaternion.Euler(0, 0, degree), Time.deltaTime);
}
}
I have two ThirdPersonController characters.
When the event OnTriggerEnter is trigger i see in c.Name "ThirdPersonController"
I also added 4 empty gameobjects each one added a box collider set IsTrigger on and also attached each gameobject this script.
And i checked when the character get to the wall they stop moving but keep walking on place.
Now i want at this point that the current character( or both ) that triggered the event to rotate 180 degrees. But instead it's not making rotation the character/s keep walking out of the terrain in some degree changed on the z axis i think.
I guess i did something wrong with the Quaternion.Slerp line.
Use Collider.gameObject
As you have two gameobjects with the same name, your GameObject.Find(c.name) line will always be returning the same one, regardless of which Collider actually triggered the collision.
GameObject.Find is also very slow in comparison to directly using the gameObject property of Collider, so you'll want to avoid using Find as often as possible.
Here's a modified version:
void OnTriggerEnter(Collider c)
{
// Don't use GameObject.Find here - just use the gameObject ref on the given collider:
GameObject character = c.gameObject;
character.transform.rotation = Quaternion.Slerp(character.transform.rotation, Quaternion.Euler(0, 0, degree), Time.deltaTime);
}
Time.deltaTime is for Update only
It's just a fairly random, very small number otherwise.

OnCollisionEnter somehow not working [duplicate]

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:

2D Collision & Stop in Unity 3D

I have a simple scene in 2D. The right yellow box is the "Player", while the green & brown thing is the "Obstacle".
Player has a BoxCollider2D, RigidBody2D and a C# script named Hero.cs attached to it. BoxCollider2D enabled Is Trigger; RigidBody2D enabled Is Kinematics; other settings are left in default values.
Obstacle has only a BoxCollider2D with Is Trigger enabled.
and here is the Hero.cs:
using UnityEngine;
using System.Collections;
public class Hero : MonoBehaviour {
public float moveSpeed = 0.1f;
private Vector3 moveDirection;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 currentPos = transform.position;
if(Input.GetKey("left")) {
transform.Translate(new Vector3(-1, 0, 0));
} else if(Input.GetKey("right")) {
transform.Translate(new Vector3(1, 0, 0));
}
}
void OnCollisionEnter2D(Collision2D collision) {
Debug.Log("Colliding");
}
void OnTriggerEnter2D(Collider2D other) {
Debug.Log("Triggering");
}
}
Only "Triggering" appears in Console Log.
My question is: What should I add to make the "Player" inaccessible to the "Obstacle" (no need to bounce away)?
Note: Using Unity 4.5
Update: After I set Gravity Scale to 0, collision detection works, but in a strange way. The "Player" go sideway during collision. Watch this YouTube video for action.
I expect the Player only go along X or Y axis. What did I miss ?
IsTrigger
Triggers let other colliders pass through without any collision happening. They are only triggering an event, hence the name.
If you disable IsTrigger for both objects, you will get collisions and the corresponding events are fired.
More infos here: http://docs.unity3d.com/Manual/CollidersOverview.html
IsKinematic
Kinematic rigidbody colliders will only collide with other non-kinematic rigidbody colliders.
Have a look at this matrix http://docs.unity3d.com/Manual/CollisionsOverview.html
Disable IsKinematic and move the player with MovePosition if you don't want to use force values to move the player.

Categories