Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
1
Question by Roland09 · Jul 15, 2016 at 12:35 PM · rotateparent-child

Rotate turret with multiple barrels towards a target and fire

The short version:

I need to rotate a child towards a target, the parent should rotate with it.

The long version:

I have a turret with multiple barrels. Think of it as a ball with multiple cylinders sticking out of it. The cylinders are positioned and rotated arbitrarily.

The cylinders should be selected randomly, the parent rotated towards the target so that the child cylinder faces the target and then the cylinder should fire at the target.

Example image:

alt text

I found some helping code here on the forum, but unfortunately that one works only as long as the z axis isn't involved.

This is the code I've come up with so far:

 using UnityEngine;
 using System.Collections;
 
 public class RotateTowardsTargetAndFire : MonoBehaviour {
 
     [Tooltip("The target towards which to rotate.")]
     public Transform target;
 
     [Tooltip("Speed at which to rotate towards target.")]
     public float rotateSpeed = 100;
     
     [Tooltip("The list of directions / barrels which will be used.")]
     public GameObject[] direction;
 
     // Current direction array index.
     private int currentDirectionIndex;
 
     void Start()
     {
 
         if( direction.Length == 0)
         {
             Debug.LogError("Direction mustn't be empty!");
         }
 
         NextRandomDirectionIndex();
 
     }
 
     void Update () {
 
         RotateAndFire();
 
     }
 
     /**
      * Rotate parent towards target, but using the child for the rotation calculation
      * source partially from: http://answers.unity3d.com/questions/715123/rotate-parent-to-aim-child.html
      */
     void RotateAndFire()
     {
         // get current destination
         GameObject child = direction[currentDirectionIndex];
 
         // rotate parent towards the direction into which the child faces when it looks at target
         Vector3 angles = child.transform.localEulerAngles;
         Quaternion m_parentToChild = Quaternion.Euler(-angles.x, -angles.y, -angles.z);
         Quaternion lookRotation = Quaternion.LookRotation(target.transform.position - transform.position);
         Quaternion finalRotation = lookRotation * m_parentToChild;
 
         transform.rotation = Quaternion.RotateTowards(transform.rotation, finalRotation, rotateSpeed * Time.deltaTime);
 
         // angle to check if we are close enough with the rotation
         float angleDiff = Quaternion.Angle(transform.rotation, finalRotation);
 
         // fire bullet and get next direction
         if(angleDiff < 0.1f)
         {
             // debug ray / fire bullet
             DebugRay();
 
             NextRandomDirectionIndex();
 
         }
     }
 
 
     /**
      * Get the next random direction.
      * Ensure that it is different to the current one
      */
     private void NextRandomDirectionIndex()
     {
 
         // get next index
         int nextIndex = Random.Range(0, direction.Length);
 
         // ensure that the next index is different to the current one
         if ( currentDirectionIndex == nextIndex)
         {
             nextIndex++;
         }
 
         if( nextIndex >= direction.Length)
         {
             nextIndex = 0;
         }
 
         currentDirectionIndex = nextIndex;
 
     }
 
     private void DebugRay()
     {
         float length = 5;
         float duration = 2;
 
     GameObject child = direction[currentDirectionIndex];

     Vector3 forward = child.transform.TransformDirection(Vector3.forward) * length;

     Debug.DrawRay(child.transform.position, forward, color, duration);
 
     }
 
 }

As long as I rotate the cylinders in design mode only in X and Y direction, everything is fine, but if I rotate around Z, the calculations are off and the shots, i. e. the debug rays go into the floor and in the sky instead of at the target.

Does anyone know how to solve that problem, i. e. rotate the parent so that the child faces a target and then fire a bullet in the direction of the target?

Thank you very much for the help!

turret.jpg (19.6 kB)
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Roland09 · Jul 15, 2016 at 05:22 PM

Solved it thanks to this and this post. In case someone else needs it, here's the relevant code:

 Quaternion relativeRotation;
 
 ...
 
     private void NextRandomDirectionIndex()
     {
         // get next index
         int nextIndex = Random.Range(0, direction.Length);
 
         // ensure that the next index is different to the current one
         if (currentDirectionIndex == nextIndex)
         {
             nextIndex++;
         }
 
         if (nextIndex >= direction.Length)
         {
             nextIndex = 0;
         }
 
         currentDirectionIndex = nextIndex;
 
         GameObject child = direction[currentDirectionIndex];
 
         relativeRotation = Quaternion.Inverse(transform.rotation) * child.transform.rotation;
     }
 
     void RotateAndFire()
     {
 
 
         GameObject child = direction[currentDirectionIndex];
 
         Vector3 targetDir = target.transform.position - child.transform.position;
         Quaternion lookRotation = Quaternion.LookRotation(targetDir);
         transform.rotation = Quaternion.RotateTowards(transform.rotation, lookRotation * Quaternion.Inverse(relativeRotation), rotateSpeed * Time.deltaTime);
 
         float angleDiff = Quaternion.Angle(child.transform.rotation, lookRotation);
 
         // fire bullet and get next direction
         if (angleDiff < 0.1f)
         {
 
             // debug ray / fire bullet
             DebugRay();
 
             NextRandomDirectionIndex();
 
         }
 
     }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Crashjumper · Jul 15, 2016 at 03:35 PM

Try messing around with an empty game object at the parent. The turret base model as a child of that. Another empty game object as the child of the first game object. With the two barrels as the child to that game object. The parent will have a horizontal rotate script for the turret base movement. the barrels game object will have a vertical movement script. the rotation ahould use localrotate.

Here is a example layout. Game object Turret base model Horizontal movement script Game object Vertical movement script Barrel Barrel

I will add more when later today once i get home, as i have an example on my pc.

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Roland09 · Jul 15, 2016 at 03:43 PM 0
Share

Thanks, an example would be great. I'm confused with horizontal and vertical rotation, the rotation should be in any direction, since the turret is a flying ball with barrels.

avatar image Crashjumper Roland09 · Jul 15, 2016 at 04:03 PM 0
Share

Sorry i though the barrels rotated independently. If you are using raycasts or your projectiles are 3x to 5x faster then the target you could use a lerp or slerp lookat

Example http://wiki.unity3d.com/index.php/SmoothLookAt_CS

See if this helps.

avatar image Roland09 Crashjumper · Jul 15, 2016 at 04:27 PM 0
Share

Thanks, unfortunately it doesn't solve the problem.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Rotating object relative to player to orient it center of camera regardless of direction. 0 Answers

How can I add rotations to transform.rotation? 0 Answers

Rotation animation worked in Unity 4.6, broke in 5.3.5+ 0 Answers

Object orientation remains the same while rotating object 1 Answer

NavMesh, wait for rotation before moving 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges