- Home /
Move object in front of another
How can you move an object to another but have it go in front of the other object. (in front of the target)
Here is the code I wrote that moves the object to my hand:
void OnMouseUpAsButton() {
target = GameObject.Find("hand");
transform.position = new Vector3(target.transform.position.x, target.transform.position.y, target.transform.position.z);
transform.parent = target.transform;
}
How depends on what you mean by "in front." It could be simply offsetting on the Z axis, or it could be in relation to the camera, or it could be in relation to the forward vector of the target. Also how much in front?
in relation to the camera and in front just enough so it touches the hand and doesnt go inside of the hand. (on the edge of the hand)
Answer by robertbu · Jan 16, 2013 at 05:11 PM
This code casts a ray from the target to the camera and then places the game object 'distance' from the target's origin toward the camera.
Ray ray = new Ray(target.position, Camera.mainCamera.transform.position - transform.position);
transform.position = ray.GetPoint(distance);
Note if you are really using a hand, and if that hand rotates a lot, things might look weird. For example, if the hand is turned around backwards, then the ball will be 'distance' towards the camera from the back of the hand. And since a hand is not uniform, if the hand is turned sideways, the ball likely will be in the hand. I'm not sure what you are doing, but if the ball is of a fixed size, and if you want the ball in the palm of the hand, you might be better off creating an empty game object, make the empty game object a child of the hand, move the empty game object so that it is above the palm of the hand, and then use this empty game object as the target.
Your answer
Follow this Question
Related Questions
How to move a cube to another cube 2 Answers
Decrease distance between 2 objects 3 Answers
How to move an object in world with script 1 Answer
Animate an object to a new position... 1 Answer
Will this code move an object 2 Answers