- Home /
rotate towards a raycast hit point
hi, I`m trying to make a flight game that works like war thunder with the mouse controls, if you don`t know what is war thunder it is that the plane rotates towards a point set by the mouse position, and the only way i could think on doing it is with a raycast like the following(im a noob with raycasting)
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 1000)){
var rotationLookAt = Quaternion.LookRotation(transform.position, hit.point);
Quaternion.Slerp(transform.rotation, rotationLookAt, 6);
}
please tell me if what am I doing wrong, or if there is a better way. thanks a lot
Answer by whydoidoit · Mar 31, 2013 at 07:28 PM
That sounds like a good start to me - normally you will define some plane onto which you wish to cast the ray and set the position.
The best way of just checking that plane is to:
Make it a box collider for simplicity
Use that box collider's ray cast function to get the position.
This is faster as you only check the one collider and won't have a problem if something is in the way.
If you wanted to set the elevation of an aircraft you might want to make it a box of colliders that follows your camera around (obviously you don't need the face behind you. That way clicking anywhere would cause the aircraft to turn, including upwards etc.
Answer by MountDoomTeam · Mar 31, 2013 at 07:46 PM
perhaps you could do an approach of this kind:
assume that there is a straight line going through the plane travel direction, and then when you click the point on the screen/hover over a point on the screen, you will have another line, either going from the aeroplane or the camera to the mouse position.
you get the point of the mouse position with this function http://docs.unity3d.com/Documentation/ScriptReference/Camera.ScreenToViewportPoint.html one of the camera functions
And then you have 2 lines, the line aeroplane is facing and the new line , and interpolate between the 2 lines.
that said, I'm not exactly sure about the screen to worlds position... http://docs.unity3d.com/Documentation/ScriptReference/Camera.ScreenToWorldPoint.html
I think there is a way to make a raycast jump through everything that doesn't have a certain tag, in which case you could make the skybox have a inwards Collider and to use that? like if you have a giant box, I would understand the above explanation .I was a bit confused about where the plane he was talking about would be.
if you have to make an object that stays in front of the aeroplane and that shows where the mouse position is, you would have the position of that mouse object anyway, and take that relative to the plane and interpolate it.