- Home /
Move rigid body using explosion force in C#
I am really new to unity and coding so I might be going about this the wrong way but I'm trying to set it up so that when the user touches a point on his screen, an explosion occurs and throws a box (onscreen rigidbody gameobject) in the opposite direction. I am wanting the force to occur at the point where the user touches the screen and the farther the touch and is from the object, the weaker the force. I am using Overlap.Sphere for detection and AddExplosionForce to add force to the box. Right now, nothing is happening when I touch the screen. (I am also wanting the box to move only in x,y axis, but I dont know how to do that, or even if that is possible) I am sure that there are packages out there that can do this, but I am really wanting to learn how to code and to figure/understand why my code isnt working.
Since I am very very new, if there is something wrong with my code, could you please provide the correct code that I would need to use since Im not sure if I would be able to figure out how to implement them into my code on my own. Any help would be greatly appreciated.
public class PlayerMovement : MonoBehaviour {
public float radius = 10.0F;
public float power = 10.0F;
// Use this for initialization
void Start () {
}
void Update () {
for (int i = 0; i < Input.touchCount; i++)
{
Touch touch = Input.GetTouch(i);
// -- Tap: quick touch & release
if (touch.phase == TouchPhase.Ended && touch.tapCount == 1)
{
// Touch are screens location. Convert to world
Vector2 touchPos = Input.GetTouch(i).position;
// convert touch's screen position to world coordinates
// z position is 10, camera is set to -10
Vector3 worldPos = Camera.main.ScreenToWorldPoint(new Vector3(touchPos.x, touchPos.y, 10));
// Effect for feedback
Collider[] colliders = Physics.OverlapSphere(worldPos, radius);
foreach (Collider hit in colliders) {
if (hit.attachedRigidbody)
hit.attachedRigidbody.AddExplosionForce(power, worldPos, radius, 3.0F);
}
}
}
}
there is a free package on the asset store which does exactly what you are asking it is called "true explosions"
Usually the camera is at -10 on the z-Axis to the actual game, which happens on z == 0. When transfor$$anonymous$$g the touch.position into the world, it is at the near clip plane of the cam, far away from the game. set the touch positions z to negative camera.position.z before transfor$$anonymous$$g it into the scene