- Home /
Raycasting from child weird behaviour
Sorry if this has appeared before but I couldn't find anything. I want to raycast from a child object towards the direction it's facing. It's rotation is changed by it's parent object accordingly but I think something is wrong. Here is the code:
RaycastHit hit2;
if (tip != null) {
if (Physics.Raycast (tip.position,tip.TransformDirection(1, 0, 0) , out hit2)) {
Debug.DrawLine(tip.position, hit2.point);
}
}
And here is the part with the rotation change:
mouseOnY = Camera.main.ScreenToWorldPoint (Input.mousePosition).y - transform.position.y;
foreach (Transform t in upperBody) {
t.localRotation = Quaternion.Euler (new Vector3 (t.rotation.x, t.rotation.y, mouseOnY));
}
I uploaded a video because the problem cannot be seen in an image.
Answer by HashGrove · Feb 21, 2015 at 07:03 PM
Sorry for wasting your time. It seem I have been rotating the parent and child at the same type so the rotations where going funky.
It's ok, but I think there is more here. Imo it's just a chance that this code works as you wanted it to. Don't get me wrong - I'm amazed why it even works :) because it really shouldn't
(Give me few moments and I will write you proper code for this)
Ok. I added proper code as a new answer. Check it out. I think that you should use. Your code is imo too messy right now and will give you more errors in the future. If you need any explanation or how to make it better, just ask.
Answer by andrew-lukasik · Feb 21, 2015 at 07:44 PM
Use this code for rotation:
Vector3 mousePositionScreen = Input.mousePosition;
mousePositionScreen.z = Mathf.Abs( Camera.main.transform.position.z );//<without setting Z (default is 0f) this Camera.main.ScreenToWorldPoint() will give the same result as Camera.main.transform.position, srsly
Vector3 mousePositionWorld = Camera.main.ScreenToWorldPoint( mousePositionScreen );
float axisRotaionTowardMouse = Quaternion.LookRotation( mousePositionWorld-upperBody.position ).eulerAngles.x;
upperBody.rotation = Quaternion.Euler( new Vector3( 0f , 0f , -axisRotaionTowardMouse ) );
To achieve better accuracy (meaning spear being more accurate in targeting mouse position) you can add similar rotation procedure to your spear Transform too:
spearTransform.rotation = Quaternion.Euler( new Vector3( 0f , 0f , -Quaternion.LookRotation( mousePositionWorld-spearTransform.position ).eulerAngles.x ) );
Your answer
Follow this Question
Related Questions
Camera follow ball along cylinder 1 Answer
Changing child's rotation changes parent's position 0 Answers
Separate child rotation 1 Answer
Make a simple tree 1 Answer
Having trouble with raycast rigidbody object childing for tractor beam 1 Answer