Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

How can I spin an object which I'm setting it's forward (like a guided bullet)

Discussion in 'Scripting' started by Follet, Dec 4, 2021.

  1. Follet

    Follet

    Joined:
    May 18, 2018
    Posts:
    38
    Hi, I can do the two things separately, make my object look where I want, and spin it on it's Z. But can't figure out how to do both:
    Code (CSharp):
    1. float spin = SpinValue;
    2. Vector3 DirectionToLook = new Vector3(Dir.x, 0, Dir.z);
    3.  
    4. //With this I make the object look where I want
    5. Object.forward = Vector3.Slerp(Object.forward, DirectionToLook, Time.deltaTime * 4);
    6.  
    7. //With this I can make it spin
    8. Object.Rotate(0, 0, SpinValue * Time.deltaTime * 10);
    9.  
    10. //Using both at the same time does not spin (as expected). How can I do it?
    Thanks in advance
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,593
    Not sure if there's a better way, but you could create a Parent container, and have that move towards the object, while the Child (the bullet) is spinning inside of the Parent.
     
    Follet likes this.
  3. Follet

    Follet

    Joined:
    May 18, 2018
    Posts:
    38
    Yeah I guess that would work, I'll try it out, thanks.
    So far I did this:

    Code (csharp):
    1.  
    2. Quaternion toRotation = Quaternion.LookRotation(DirectionToLook, Object.right);
    3. Object.rotation = Quaternion.Slerp(Object.rotation, toRotation, Time.deltaTime * 4);
    4.  
    But with that I can't control how fast that is spinning (I want control over spin speed and direction).
     
  4. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,593
    Instead of manually spinning it, you could rely on RigidBodies and their torque values to change the speed.