Search Unity

how i rotate the player with the joystick i crate

Discussion in '2D' started by thefrogeitan, Jul 23, 2020.

  1. thefrogeitan

    thefrogeitan

    Joined:
    Oct 20, 2019
    Posts:
    7
    Code (CSharp):
    1. sing System.Collections;
    2. using System.Collections.Generic;
    3. using System.Drawing;
    4. using UnityEditor;
    5. using UnityEditor.Experimental.GraphView;
    6. using UnityEngine;
    7.  
    8. public class joystick : MonoBehaviour
    9.  
    10. {
    11.     public Transform player;
    12.     public float speed;
    13.     private bool touchStart = false;
    14.     private Vector2 pointA;
    15.     private Vector2 pointB;
    16.     public Transform circle;
    17.     public Transform outerCircle;
    18.  
    19.  
    20.  
    21.     // Start is called before the first frame update
    22.     void Start()
    23.     {
    24.        
    25.     }
    26.  
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.         if (Input.GetMouseButtonDown(0))
    31.         {
    32.             pointA = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    33.             circle.GetComponent<SpriteRenderer>().enabled = true;
    34.             outerCircle.GetComponent<SpriteRenderer>().enabled = true;
    35.  
    36.             circle.transform.position = pointA;
    37.             outerCircle.transform.position = pointA;
    38.         }
    39.  
    40.  
    41.        
    42.  
    43.  
    44.  
    45.         if (Input.GetMouseButton(0))
    46.         {
    47.             pointB = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.z));
    48.             touchStart = true;
    49.         }
    50.         else
    51.         {
    52.             touchStart = false;
    53.             circle.GetComponent<SpriteRenderer>().enabled = false;
    54.             outerCircle.GetComponent<SpriteRenderer>().enabled = false;
    55.         }
    56.  
    57.     }
    58.  
    59.     private void FixedUpdate()
    60.     {
    61.         if (touchStart)
    62.         {
    63.             Vector2 offset = pointB - pointA;
    64.             Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f);
    65.             movePlayer(direction);
    66.             circle.transform.position = new Vector2(pointA.x + direction.x, pointA.y + direction.y);
    67.         }
    68.        
    69.     }
    70.     void movePlayer(Vector2 direction)
    71.     {
    72.         player.Translate(direction * speed * Time.deltaTime);
    73.     }
    74. }
    75.