Search Unity

Tank turret rotate, gun elevate, to aim at mouse pointer (unity 5)

Discussion in 'Scripting' started by Ghidera, Jul 31, 2015.

  1. Ghidera

    Ghidera

    Joined:
    Mar 6, 2013
    Posts:
    53
    I've been messing around with this for a while and I'm stuck/lost in the many possibilities.

    I've been playing with a tank model and pretty easily had it rotate locally when the mouse pointer is to the left or right of center screen. What I'd like to do is have the turret rotate AND the mouse pointer move toward center screen so that the turret doesn't rotate endlessly.

    I've found some examples that seem to half-work and have lots of jitters (perhaps its something to do with older versions of unity?).

    I don't necessarily need the entire thing written for me, just point me at appropriate methods.

    For instance, while looking for a method to rotate the turret on its local axis and found a gazillion non-working examples. Eventually I found out that transform.rotate() defaults to local rotation and you have to actually specify world space if you don't want local - very simple really but difficult to find in googleland.
     
  2. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    There's like four different functions that all do pretty much what you want. I mean, I don't know about assigning values to the mouse cursor directly or anything, you'll have to figure that one out, but the movement itself can be accomplished just by taking the cursor's position (a screen point, which is a pixel position where bottom left is the origin) and using "Camera.ScreenToViewportPoint()" with that position as a parameter.

    That gives you the Viewport Point of the same location, what's essentially a 0 to 1 value for x and y, like a screen percentage (bottom-left is still the origin though). Then you take that and use Lerp, MoveToward, or SmoothDamp depending on your preference (look them up in the manual) to move them closer to a viewport point of X: .5f / Y: .5f . Then you translate it back into a Screen Point (pixel position) and assign it back to the mouse position.
     
    Last edited: Jul 31, 2015