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 To Make it Aim in Right Direction?

Discussion in 'Scripting' started by CunningLobster, Oct 7, 2021.

  1. CunningLobster

    CunningLobster

    Joined:
    Jun 25, 2020
    Posts:
    10
    Hi! I try to make a shooting system in my game and I can't figure out how to make my character aim in right direction.

    As you can see in the video above a red line, which represents the aiming direction, doesn't match a mouse position. To achieve the result I just rotated the gun around Z axis using such expression:
    Code (CSharp):
    1. gun.transform.rotation = Quaternion.Euler(0, 0, touchControlsManager.TouchPosition().y);
    But It doesn't work fine. Could somebody help me to calculate the aiming direction according a mouse position?
     
  2. Lekret

    Lekret

    Joined:
    Sep 10, 2020
    Posts:
    272
    Your code is wrong. If you have your weapon in let's say (0, 0) point, then if your touch position is (1, 1), then the result angle should be 45 angles relative to the ground. Then let's say you move your mouse in (2, 2) point, angle should still be 45 angles, but in your case it would different, world positions have nothing to do with euler angles which is simple 360 angle system.
    In your case you need something like:
    Code (CSharp):
    1. transform.LookAt(mousePosition)
     
    CunningLobster likes this.
  3. CunningLobster

    CunningLobster

    Joined:
    Jun 25, 2020
    Posts:
    10
    Unfortunately such expression is not relevant for me because LooAt oriented to Z axis. But I started searching for LookAt for Vector2 and found that solution: