- Home /
Yet another turret control thing (5.5.1f1)
This is for school. So the assignment prescribes a flying vehicle with two turrets on the front. The vehicle constantly moves forward. But the problem is with two turrets, they have to basically have different rotations and also not turn the camera much (if at all)
I was thinking of having them look at a plane far away from the vehicle and just go from there. But the assignment also includes colliding with enemies. So somehow I have to make the enemies spawn and then creep towards the player.
Then targeting them with the plane won't necessarily work. I saw some questions kinda in the same vein but they were in javascript and also not exactly what I needed. So, is there a way in C# to track the mouse position on the canvas and convert it to world space so the turrets will aim at whatever the mouse is over?
Answer by armorhide406 · Apr 07, 2017 at 03:01 PM
Took some doing... Basically create a ray, make it based on the main camera and check hits. Then turn the turrets to face where it hits. Hope this helps people.
RaycastHit rayHit;
void Update()
{
int layerMask = 1 << 8;
// Bit shift the index of the layer (8) to get a bit mask
layerMask = ~layerMask;
// This would cast rays only against colliders in layer 8, which is set to Player.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
Ray aimRay = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0)); //generate ray
if (Physics.Raycast(aimRay, out rayHit, targetRange, layerMask))
{
Debug.DrawRay(aimRay.origin, aimRay.direction * 100.0f, Color.green, 0.1f);
Debug.Log(rayHit.collider.name);
Vector3 hitPosition = rayHit.point; //track hit
gunRotation = Quaternion.LookRotation(transform.position - rayHit.point, Vector3.down);
//set aim to hit, Vector3.down because imported object is upside down and backwards
//you can use
transform.rotation = Quaternion.Slerp(transform.rotation, gunRotation, turnSpeed * Time.deltaTime);
//transform object with slerp to not make it snap to whatever it's looking at
}
}
Answer by Rhombuster · Apr 07, 2017 at 02:18 AM
I'll give you some hints that should help you:
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html https://docs.unity3d.com/ScriptReference/Camera.ScreenToWorldPoint.html
Let me know if you have other questions.
Your answer
Follow this Question
Related Questions
Rotating child object around X and Z from different angles causing issues 2 Answers
Difference between transform.localRotation = Quaternion and transform.RotateAroundLocal 2 Answers
How can I control the yaw, pitch and roll of a flying object? 0 Answers
Keep rotation of not parented item carried by player relative to first person player camera 1 Answer
Rotation acting weird 1 Answer