- Home /
Trouble Descaling 2D object
Hi, I'm trying to make a game where one has to catch bars of soap. I want the player to catch the soap and hold it until it shrinks to a fraction of its original size.
This mechanic works for the most part, but once I reach a certain threshold, it shrinks down to the minimum size on its own, and I don't know why. Below is a video demonstrating the problem as well as the relevant code.
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewSoap : MonoBehaviour {
public float hp = 300;
float totalHp;
public float minHp;
float scaler;
private bool isCaught = false;
Vector3 originalScale;
// Use this for initialization
void Start() {
totalHp = hp;
originalScale = new Vector3(GetComponent<Transform>().localScale.x, GetComponent<Transform>().localScale.y, GetComponent<Transform>().localScale.z);
}
// Update is called once per frame
void Update() {
print("health: " + hp + "|| scaler: " + scaler);
if ((hp >= minHp) && isCaught)
{
hp--;
scaler = hp / totalHp;
GetComponent<Transform>().localScale = originalScale * scaler;
}
else if( hp <= minHp)
{
// Destroy(gameObject);
}
}
void OnTriggerStay2D(Collider2D other)
{
if ((other.name == "Hand") && (other.GetComponent<Hand>().isOpen() == false))
{
isCaught = true;
print("Caught!!");
}
else
{
isCaught = false;
}
}
void onTriggerExit2D(Collider2D other)
{
if (other.name == "Hand")
{
isCaught = false;
}
}
}
Any help would be greatly appreciated, thank you!!
Answer by TheSOULDev · Sep 20, 2017 at 08:49 PM
You should use OnTriggerEnter instead of OnTriggerStay, use coroutines instead of Update, and then see if your bugged code is fixed. You can see that the way you constructed it doesn't work well as it is possible to set isCaught to true twice consecutively. Also since we don't have insight in the variables that actually matter, people probably can't tell you what other than the lousy implementation is wrong as the booleans that control the behaviour are not shown in the video. My guess is that because you implemented it in a way you did, your isCaught never set itself to false, as it seems to be the only way you would get the behaviour you're getting if there's no other script interfering.
Your answer
Follow this Question
Related Questions
Rigidbody2D.velocity out of controll 3 Answers
Why my triggers don't collide? 2D 0 Answers
Collision with renderer.enabled? 0 Answers
Simple movement problem. Need units to stop dead on collision. 3 Answers
Checking trigger/collision of another gameobject separate from the one the script is on 1 Answer