Stop movement on collision
Hi. I'm hoping someone can help me out here, I'm new to unity. I have a 2d game with moving walls to create the impression that the player is moving. When the player hits the wall I want the walls to stop moving. I've tried adding code to stop the script on collision but it doesn't seem to do anything (the walls just keep moving). Any advice as to what i've done wrong? Thanks. Heres my code for the walls:
using UnityEngine;
public class ObjectMove : MonoBehaviour
{
void FixedUpdate ()
{
transform.position = new Vector3(transform.position.x - 0.045f, transform.position.y , 0);
if (transform.position.x <= -8.5f)
{
Destroy(gameObject);
}
}
void OnTriggerEnter2D(Collider2D col)
{
gameObject.GetComponent<ObjectMove>().enabled = false;
}
}
Answer by Dsiak · Dec 03, 2021 at 01:44 AM
I think there is a lot to unpack here, lets go. First of all if nothing is happening on collision the game objects are probably set up incorrectly, make sure at least one of the parties involved have a "Rigidbody2D" attached to it and that the player(The object that is going to touch the wall who is expecting to touch a trigger) is marked as trigger. That would activate the OnTriggerEnter2D function. Now you said walls on plural but that will only disable the script on the wall the player collided with while the others will keep on walking like nothing happened, you probably want to grab all the objects with a "ObjectMove" attached and execute a function what makes it stop walking (That is better practice them disabling the whole script). I took the liberty to build a rough example
public class ObjectMove : MonoBehaviour
{
//Control variable
bool isActive;
private void Start()
{
//starts active by default
isActive = true;
}
void FixedUpdate()
{
//Only moves is isActive is true
if (isActive)
{
transform.position = new Vector3(transform.position.x - 0.045f, transform.position.y, 0);
}
if (transform.position.x <= -8.5f)
{
Destroy(gameObject);
}
}
private void ToggleActive(bool isActive)
{
//this is active = parameter isActive
this.isActive = isActive;
}
void OnTriggerEnter2D(Collider2D col)
{
//Grab all ObjectMove in the scene
ObjectMove[] walls = FindObjectsOfType<ObjectMove>();
//Toggles off active in every object
foreach (ObjectMove wall in walls)
{
wall.ToggleActive(false);
}
}
}
This isn't peak performance but should be a problem as long as there aren't that many game objects in the scene.
Your answer
Follow this Question
Related Questions
1st Person shooter, move player forward where cam is facing 1 Answer
Skid steer type movement 1 Answer
Fix Player Movement Script,Fix Player Movement 0 Answers
What is the best way to make moving obstacles in a 3d game? 0 Answers
Cant find why character doesnt move forward with this movement script 0 Answers