0
\$\begingroup\$

I don't want to use a script with OnTriggerEnter or something like that but to simulate the red cube as a wall and when the blue cube collider hit the red cube collider it should stop. Both cubes have a box collider and on both the Is Trigger is checked true I also tried one of them or both when not checked true. And both colliders size on Z set to 3.

But the blue cube is getting to the red one and not stop when colliding :

Cubes

The blue cube is getting inside the red one :

Cubes

I tried to add a rigidbody to the moving cube the blue cube but if using Is Kinematic same behaviour if not using Is Kinematic the blue cube is falling down.

This is the script attached to the blue cube to move it to the target red cube :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObject : MonoBehaviour
{
    public GameObject target;
    public float speed;

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, target.transform.position, Time.deltaTime * speed);
    }
}

I want that the blue cube will stop when colliding the red cube collider that's why I set them on Z to 3. I don't need physics for now.

Do I need must using OnTriggerEnter in my script for that ?

I thought I tried it too but this seems to be working : Both box colliders on the cubes unchecked set false the is trigger and I added a rigidbody to the moving cube the blue one and unchecked the use gravity and now it seems to be working.

So I need a rigidbody even if I'm not using physics. I wonder why.

This is working

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The cube wont stop as you are moving by changing the transform. That will just override physics.

You need to move the cube ONLY with physics to avoid this issue. If you don't then you need the moving cube to have a collider (non trigger) and the "wall" to have a trigger collider that will, when this cube is detected, tell it to stop moving. Both may then require a rigidbody set to "Is Kinematic"

To summarise. Move the cube with physics by using something like the Rididbody.MovePosition method. If you want to move without physics you need to use triggers correctly to simulate this.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .