- Home /
Click an object to applyforce in different directions.
I can applyforce to a gameobject and have it go in 1 direction when i click on it. With something like this
rigidbody2D.AddForce(transform.up * speed);
however i want to click on the object and apply force in different directions depending on where i click on the object.
so for example clicking the green portion of the object will apply force to the right and up. while blue will apply force to the left and up. and the majority of the middle will just apply force upwards. Perhaps i can create colliders as children and send message to the main object to applyforce in a certain direction? there has to be an easier way to do this.
Answer by fighder · May 10, 2015 at 08:43 PM
You simply get the direction of the mouse to the game object and apply force base on the direction:
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 dir = gameObject.transform.position - mousePos;
rigidbody.AddForce(dir.normalized * force, ForceMode.Impulse);
so i've attempted your suggestion which makes perfect sense but i'm getting a NullReferenceException: Object reference not set to an instance of an object Error.
I'm not sure whats missing, the rigidbody is attached to the obj.
I moved the forceapplying to the object script with a function void Touched(Vector3 data){ rigidbody.AddForce(data.normalized * power, Force$$anonymous$$ode.Impulse); }
nope im stupid. got it missing this line if( Physics.Raycast(ray, out hit, 1000) )