- Home /
Touch input to move rigidbody using explosion force in C#
I am really new to unity and coding so I have been picking up snippets of code from other places and trying to put it together to make it work for my project.
I'm trying to set it up so that when the user touches a point on his screen, an explosion occurs and throws a 3D cube in the opposite direction. I created a 3D cube object and set it as a rigidbody and a larger 3D rectangle to act as the floor/ground (I did not set the larger rectangle as a rigidbody). Both of these objects have the box colliders that automatically come with the objects when you create them. 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 and AddExplosionForce to try and move the cube. 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)
{
// Get current touch location
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));
// Explosion Effect
Collider[] colliders = Physics.OverlapSphere(worldPos, radius);
foreach (Collider hit in colliders) {
if (hit.attachedRigidbody)
hit.attachedRigidbody.AddExplosionForce(power, worldPos, radius, 3.0F);
}
}
}
}
Are you sure both bodies have colliders?? If not then attach respective colliders to bodies.
Your answer
Follow this Question
Related Questions
Move rigid body using explosion force in C# 0 Answers
RigidBody immediately stops after AddForce 1 Answer
Unity Physics On Input Issue? 0 Answers
Strange Rigidbody Behavior 0 Answers
Collisions causing Rigidbody to go Haywire and move randomly. 1 Answer