Hey all,
I’m currently working on something and have hit a bit of a snag. I’m trying to set it up so that when the user touches a point on his screen, a flower petal (onscreen gameobject) moves in the opposite direction.
The way I imagined it - I wanted to run a check for any “flower” gameobjects within a “X” - pixel radius and, if positive, apply force to the petal in the opposite direction of the touch (with power inversely proportional to the distance.)
Mechanically, I figured
a) touch instantiates an empty / invisible gameobject that performs a check within a given radius for any “flower gameobjects.”
b) if positive, it emits force in a direction towards the petal inversely proportional to it’s distance (meaning that the emitted force grows weaker depending on how far away it is from the petal.
c) after emitting its force, the object destroys itself.
After looking through the script reference, I decided to use Overlap.Sphere for detection and AddExplosionForce to add force to the petal.
Using the code below, I attached a script to a placeholder object (a sphere) and made it that a mouse click caused this object to add force to the petal if it was in range. Force was inverse to distance. The problem I’m having is that explosion force adds force from the bottom of the game object - pushing it up. It looks awkward when you tap above the petal and it shoots upward.
Are there any other alternatives to AddExplosionForce? I like how the strength tapers off with distance and it seems like a decent fix. (Mostly because I haven’t found how to use AddForce in a conditional statement.) Or, if I may be so bold, do you see a better way to do this?
Code is as follows:
using UnityEngine;
using System.Collections;
public class Exploder : MonoBehaviour
{
public float radius = 5.0f;
public float power = 10.0f;
GameObject flower;
void Start()
{
flower = GameObject.Find("Flower");
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse button down!");
Detector();
}
}
void Detector()
{
Debug.Log("Detector on.");
Collider[] objectsInRange = Physics.OverlapSphere(transform.position, radius);
foreach (Collider hit in objectsInRange)
{
if (!hit)
Debug.Log("Miss!");
if (hit.rigidbody)
hit.rigidbody.AddExplosionForce(power, transform.position, radius, 3.0F);
Debug.Log("Hit " + hit.rigidbody);
}
}
}
As tempting as it is, I’m not asking you to write this out for me in code. If you could suggest alternatives to AddExplosionForce or a different approach in general, I’ll try to muddle through it on my own (since I’m still learning C# and Unity.)
Thanks for taking the time to respond!
BKF