- Home /
Question by
EyadThedevelopingBoi · Jul 15, 2020 at 08:47 AM ·
c#collisionfunctionobjectscollision2d
Interesting collision question
So I am trying to make a tower game where you try to pile up a load of objects to build a tower, the objects will have certain masses and maximum weight handling when reached the object will get destroyed
I have got the basics down, however there are still certain problems, Objects Can't lose weight, Because they are colliding with the road OnCollisionExit won't work, any suggestions?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PushDownWeightScript : MonoBehaviour
{
public float CurrentMassAboveAndWithin;
public float MaximumMassSupported;
private int Objectsbelow;
public Rigidbody2D rigidbody;
void Start()
{
CurrentMassAboveAndWithin += rigidbody.mass;
}
// Update is called once per frame
void Update()
{
if (CurrentMassAboveAndWithin > MaximumMassSupported)
{
Destroy(this.gameObject);
}
}
private void OnCollisionStay2D(Collision2D collision)
{
if (collision.gameObject.tag =="Object" && collision.gameObject.transform.position.y < transform.position.y)
{
PushDownWeightScript OtherObjectScript = collision.gameObject.GetComponent<PushDownWeightScript>();
PushDownWeightScript ThisObjectScript = this.gameObject.GetComponent<PushDownWeightScript>();
OtherObjectScript.CurrentMassAboveAndWithin = ThisObjectScript.CurrentMassAboveAndWithin / Objectsbelow;
}
if (collision.gameObject.tag == "Object" && collision.gameObject.transform.position.y > transform.position.y)
{
PushDownWeightScript OtherObjectScript = collision.gameObject.GetComponent<PushDownWeightScript>();
PushDownWeightScript ThisObjectScript = this.gameObject.GetComponent<PushDownWeightScript>();
ThisObjectScript.CurrentMassAboveAndWithin += OtherObjectScript.CurrentMassAboveAndWithin;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Object" && collision.gameObject.transform.position.y < transform.position.y)
{
Objectsbelow += 1;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject.tag == "Object" && collision.gameObject.transform.position.y < transform.position.y)
{
Objectsbelow -= 1;
PushDownWeightScript OtherObjectScript = collision.gameObject.GetComponent<PushDownWeightScript>();
PushDownWeightScript ThisObjectScript = this.gameObject.GetComponent<PushDownWeightScript>();
OtherObjectScript.CurrentMassAboveAndWithin = 1;
}
}
}
Comment