- Home /
2d Circle won't change size
I'm a beginner at coding and have tried to make a script where if one object collides with another object (otherBody), and the object is 9 times bigger and has a greater mass than otherBody, then otherBody will be destroyed, the new mass of the object will be equal to the original mass of the object + the mass of otherBody, and the new size of the object will be equal to the area of the original object + the area of otherBody. I did not get any errors in the script, attached the script to two objects, and made them collide. The if statement conditions seemed to work, the otherBody would get destroyed, and the mass of the object would be correctly changed. However, I did not see a change in the scale/size of the object visually nor numerically in the inspector. Not sure what I'm doing wrong here. Here is the code I made:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Combine : MonoBehaviour
{
public Rigidbody2D rb;
public void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
GameObject otherBody = collision.gameObject;
Rigidbody2D rbOtherBody = otherBody.GetComponent<Rigidbody2D>();
float radiusOtherBody = otherBody.transform.localScale.x / 2;
float radius = transform.localScale.x / 2;
Vector2 Size = transform.localScale;
Vector2 sizeOtherBody = otherBody.transform.localScale;
if (rb.mass > rbOtherBody.mass)
{
if(radius > 3 * radiusOtherBody)
{
Size = new Vector2(Mathf.Sqrt(Mathf.Pow(radius, 2) + Mathf.Pow(radiusOtherBody, 2)), Mathf.Sqrt(Mathf.Pow(radius, 2) + Mathf.Pow(radiusOtherBody, 2)));
rb.mass = rb.mass + rbOtherBody.mass;
Destroy(otherBody);
}
}
}
}
Your answer
Follow this Question
Related Questions
Why does my swiping code not work? 1 Answer
Character teleports upwards instead of jumping smoothly Unity2D 2 Answers
Brackeys EnemyAi Script 0 Answers
Move child closer to parent ? 1 Answer