- Home /
How to change a GameObject's direction after collision?,
I have two cubes that move back and forth. One moves on the x axis, one on the z axis. They move in different speeds and are bound to collide. Now I want them to change directions after collisions, so as to make them seem to bounce back from one another. I have added Colliders to both, but they still seem to go through the other when they meet.
This is the script for Cube1, Cube2 is the same except it moves on the z axis.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveOnX : MonoBehaviour
{
public float speed = 2.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = new Vector3(Mathf.PingPong(Time.time * speed, 5), transform.position.y, transform.position.z);
}
}
Edit: I also tried:
private void OnTriggerEnter(Collider other)
{
speed = speed * -1;
}
But it's not doing the trick
You are using transform.position to modify your objects positions, the objects will not behave like physics objects. Are these rigidbodies? If you are just using the create game object thing in Unity, you're gonna have a bad time. Rigidbodies have materials that can add bounce, I would suggest that. The alternative would be a character controller or the rigorous and daunting task of making one's own collider and control system for the cubes.
I would suggest you look into a tutorial on rigidbodies
Answer by guubebra · Oct 21, 2021 at 09:25 PM
Can you show your collider settings in the inspector?
I also tried checking the "Is Trigger" checkbox in combination with the function in the question edit, but it also didn't work.
Your answer
Follow this Question
Related Questions
Create 3d hexagonal terrain 1 Answer
Make a player only move in one direction 1 Answer
Difficulty with gaze function 0 Answers
I just discovered unity, How can i get started? 1 Answer
Prefab starts halfway through object when placed down 2 Answers