Hi all. New to Unity and C#. Been playing around for a few days and I have a quick mockup of a game where you control a marble, clicking in the direction you’d like to addForce.
I’ve created these gameObjects called “Black Holes” that suck in the player a little. They also slow down time slightly and the camera zooms in for extra effect.
The issue I’m having is when I create a duplicate of my black holes (so I can place many throughout the stage). I have a feeling I know what the problem is in the logic, but I’m unsure what would be a good fix…
Currently, with two Black Holes in the scene, only one of them triggers the time warp/zoom effect, whereas the other one just sucks in the player a little bit.
Here’s some of my code that is part of the blackhole object
void Update()
{
distanceToPlayer = Vector2.Distance(player.position, transform.position);
if (distanceToPlayer <= influenceRange)
{
// set the time scale to the variable GameSpeed, adjust the physics engine calculations (deltaTime)
Time.timeScale = GameSpeed;
Time.fixedDeltaTime = this.fixedDeltaTime * Time.timeScale;
// determine the pull force
pullForce = (transform.position - player.position).normalized / distanceToPlayer * intensity;
// if the pull force is too much, set it to the max
// otherwise just set it to what it should be
if (pullForce.x >= maxPull || pullForce.y >= maxPull){
playerBody.AddForce(new Vector2(maxPull,maxPull), ForceMode2D.Force);
} else {
playerBody.AddForce(pullForce, ForceMode2D.Force);
}
// check if game should be slowed down, return it to initial speed
} else {
if (Time.timeScale != 1){
Time.timeScale = 1;
Time.fixedDeltaTime = initDeltaTime;
}
}
}
I believe the issue is with my final else statement, which returns the game’s speed to normal. I think that the second black hole won’t trigger the effect since the first black hole is technically still out of range. Not sure why it doesn’t work the other way around though (does the first black hole have some sort of priority?). Perhaps I need to migrate this part of the code to the player to check for distances to other black holes… but I’m also unsure how I would get it to differentiate between the copies…
I’ve looked into prefabs for placing these objects, but they don’t seem to be what I’m after (since I need to reference the player in the scene)
Also unsure if this is the best way to go about placing multiple “copies” of the same GameObject in a scene in the first place (i.e. the Black Holes) but I haven’t been able to find the right vocabulary to search for an alternative.
Update: I think I’ve found a solution. Instead of using a check for Distance to Player to determine if the game should slow down, I instead used OnTriggerEnter2D to check whether the player has entered the collider of the black holes and then slowed down if collision was true.