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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Object look at touch location when moving

Discussion in '2D' started by fraykaz, Feb 27, 2020.

  1. fraykaz

    fraykaz

    Joined:
    Feb 24, 2020
    Posts:
    3
    Hi everyone,

    I am new in C# and I' am making a 2D shooter. In my videogame, I would like that my player shoot bullets when he is moving thanks to the tilt of my phone. I succeeded to code the movement of my player thanks the tilt of my phone (as u can see below) :
    Code (CSharp):
    1.     void Start()
    2.     {
    3.         rb.GetComponent<Rigidbody2D>();
    4.     }
    5.  
    6.     void Update()
    7.     {
    8.         dirX = Input.acceleration.x * moveSpeed;
    9.         dirY = Input.acceleration.y * moveSpeed;
    10.         transform.position = new Vector2(Mathf.Clamp(transform.position.x, -9.5f, 10.5f), Mathf.Clamp(transform.position.y, -5f, 5f));
    But here is my problem : I don't succeed to shoot bullet in the direction where I touch the screen at the same time. I tried, I tried so many things but nothing...
    An idea would be my player look at directly in the direction of the touch location and shoot considering that I created a gameObject "firePoint location" (which is a child of my player) to know where my bullets spawn
    but I don't know how to do....

    Any idea to solve the problem ?

    Thanks you for your attention ! :)
     
  2. fraykaz

    fraykaz

    Joined:
    Feb 24, 2020
    Posts:
    3
    SOLUTION BELOW :

    Add FixedUpdate with Vector2 and Mathf.Atan2 function.
    Here is the code :

    Code (CSharp):
    1.     void FixedUpdate()
    2.     {
    3.  
    4.         rb.velocity = new Vector2(dirX, dirY);
    5.         Vector2 lookDir = mousePos - rb.position;
    6.         float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
    7.         rb.rotation = angle;
    8.  
    9.  
    10.     }