- Home /
How do I rotate a 2D object using a joystick?
Sorry if my code is not the best as I am new to coding, so far my code allows my character to move and instantiate rockets and it works pretty well. However, I am having trouble trying to rotate my characters gun and cant find any helpful sources anywhere. I am trying to find out how to match the rotation of my joystick to my characters gun. Thanks for the help. Here is my Code:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class MyScript : MonoBehaviour {
protected Joystick joystick;
protected Joybutton joybutton;
public Rigidbody2D rb;
protected bool shoot;
public Transform firepoint;
public GameObject arrowPrefrab;
// Start is called before the first frame update
void Start()
{
joystick = FindObjectOfType<Joystick>();
joybutton = FindObjectOfType<Joybutton >();
}
// Update is called once per frame
void Update()
{
var RigidBody2D = GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(joystick.Horizontal * 10f + Input.GetAxis ("Horizontal") * 10f, joystick.Vertical * 10f + Input.GetAxis("Horizontal") * 10f);
if (!shoot && (joybutton.Pressed))
{
shoot = true;
Shoot();
}
if (shoot && !joybutton.Pressed || Input.GetButton("Fire1"))
{
shoot = false;
}
}
void Shoot()
{
Instantiate(arrowPrefrab, firepoint.position, firepoint.rotation);
}
} ,Sorry if its a bit messy as I am new to Unity, but this is my code so far, it works for moving my character around, however, I have created a new joystick and I am trying to rotate my character's gun using this while also making it fire. Basically I just need to find a way to rotate the gun.