Search Unity

Having Issues with rotation model

Discussion in 'Scripting' started by pojo1979, Feb 22, 2017.

  1. pojo1979

    pojo1979

    Joined:
    Feb 18, 2017
    Posts:
    5
    I have a problem that I don't quite understand. I have a model of an anti-aircraft tank, I want the turret to rotate toward the player. I have the following code that works well to rotate the entire tank toward the player, but when I change it to use only the turret portion of the mesh the turret turns onto it's side, see pic below

    Code (CSharp):
    1. Transform player = GameObject.FindWithTag("Player").transform;
    2.         if (player)
    3.         {
    4.             Vector3 direction_diff = (transform.position - player.position);
    5.             direction_diff.y = 0;
    6.            
    7.             Quaternion rotation = Quaternion.LookRotation(direction_diff);
    8.             transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, Time.deltaTime * rotateSpeed);
    9.         }
    upload_2017-2-21_22-41-22.png
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,035
    I would guess that your turret mesh wasn't exported with z fordward and y up.

    If you have the model you could change that in blender or 3dsm or maybe try putting the turret in an empty game object within the tank model and rotating the empty gameobject instead.
     
  3. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,089
    Quaternion.LookRotation also takes a second parameter which describes the up vector - you could try changing that to Vector3.right or Vector3.left maybe?
     
  4. pojo1979

    pojo1979

    Joined:
    Feb 18, 2017
    Posts:
    5
    The turret beginning rotation as it relates to the tank base is x =-90, y=0, z=90. I believe it's the x axis rotation that is causing the problems. When I start the game the turrent slowly goes from -90 to 0 which makes it end up like the pic. I to keep the x axis rotation at -90, but I'm too tired and can't seem to think how to do it right now.
     
  5. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    @pojo1979

    This should be pretty easy to do, I bet it's best first add some Unity empty GameObjects as "root" objects.

    One empty GameObject as root of tank, one as root of turret directional rotation, and one as root for height angle adjustment.

    Parent the gameobjects, not your meshes, and use these GameObjects to rotate meshes....

    This way you can avoid default rotation values... I'd never use mesh / object hierarchies from 3d software for hierarchies in cases like this... unless I put extra effort to make sure initial values are "zeroed out".
     
    pojo1979 likes this.
  6. pojo1979

    pojo1979

    Joined:
    Feb 18, 2017
    Posts:
    5
    @eses thank you for that tip, it makes things much easier.