- Home /
how to shoot with joystick
Hi, I been trying making 2d top down shooter for mobile using joystick. I'm using joystick pack from asset store. I don't know how to make my character shoot right when I'm moving to the right or other direction with joystick. Currently my shooting mess up really badly like joystick left shooing with right directon etc. how to make it correct direction. thanks in advance and sorry bad english. float rotateAngle; float horizontalMove; float verticalMove;
public Transform firePoint;
public Rigidbody2D bulletPrefab;
public Joystick joystick;
public float moveSpeed = 2f;
public float bulletSpeed = 100f;
private void Start()
{
rotateAngle = 0f;
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
horizontalMove = Mathf.RoundToInt(joystick.Horizontal);
verticalMove = Mathf.RoundToInt(joystick.Vertical);
Rotate();
}
void FixedUpdate()
{
//rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
transform.position = new Vector2(horizontalMove * moveSpeed * Time.deltaTime + transform.position.x, verticalMove * moveSpeed * Time.deltaTime + transform.position.y);
}
public void Shoot()
{
var bulletFired = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
bulletFired.AddForce(firePoint.up * bulletSpeed);
}
void Rotate()
{
//Top
if (verticalMove == 1 && horizontalMove == 0)
{
rotateAngle = 0f;
}
//Right
if (horizontalMove == 1 && verticalMove == 0)
{
rotateAngle = 90f;
}
//Down
if (verticalMove == -1 && horizontalMove == 0)
{
rotateAngle = 180f;
}
//Left
if (horizontalMove == -1 && verticalMove == 0)
{
rotateAngle = 270f;
}
firePoint.rotation = Quaternion.Euler(0f, 0f, rotateAngle);
}
Your answer
Follow this Question
Related Questions
rotation value resets after I release the joystick, how to fix (2d)? 1 Answer
Joystick character rotation wrong movement 1 Answer
How to shoot using the right mobile Joystick? 2 Answers
How to move player using UI buttons, when using Input.mousePosition to shooting? (Android) 0 Answers
Why isn't my joystick code working? 1 Answer