- Home /
AddForce on Object at Direction of Click
Hi there all, I'm currently struggling to AddForce to an object, the object is a Domino and what i am attempting to achieve, that when i click on either 2 of the main faces (back and front) the domino will fall in the corresponding click direction, i do not however wish for the user to be able to 'tip' the domino sideways, only backward and forward, in relation to whatever the dominos rotation may be.
This piece of code is what I started with, but it would only push the domino in one specified 'world' direction, rotation of the domino made no difference to the direction of force it would always push 'North'.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.CompareTag("Domino"))
{
hitInfo.collider.GetComponent<Rigidbody>().AddForce(transform.forward * forceAmount);
}
}
This piece of code is my current piece where I am struggling, the result with this code is that the domino 'hops' toward the camera when clicked and not at the direction that the mouse clicked.
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var mouseDir = mousePos - gameObject.transform.position;
mouseDir.z = 0.0f;
mouseDir = mouseDir.normalized;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.CompareTag("Domino"))
{
hitInfo.collider.GetComponent<Rigidbody>().AddForce(mouseDir * forceAmount);
}
}
}
Below are some GIFs, visualizing what is happening in-game.
Old Code:
New Code:
Main Point: How can i make it so if i click the face of the domino, it will fall onto the back side and clicking the back makes it fall to its face, no matter the rotation of the domino.
Answer by kolboch · Jan 18, 2019 at 04:36 PM
You have to use the normal of the object surface detected by raycast. Then you would have to reflect that vector and this will be your force you are willing to apply. Useful docs: https://docs.unity3d.com/ScriptReference/RaycastHit-normal.html
Answer by xxmariofer · Jan 18, 2019 at 04:37 PM
the easiest way of fixing this is to have 2 childs colliders front face and behind with 2 tags and compare the tag and use your old code but depending on the tag assigned force in Vector3.right and left.
this would be great, yet, if i rotated the do$$anonymous$$o, it will still be pushing it 'Left' relative to world space, not the objects local position
i think you confused Vector3.forward (0,0,1) always the same and transform.forward that is the forward vector of the object and changes if you rotate it.
With this code:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
if (hitInfo.collider.CompareTag("Do$$anonymous$$o"))
{
hitInfo.collider.GetComponent<Rigidbody>().AddForce(transform.forward * forceAmount);
}
}
I Get this Result:
Is this what you mean?