Note: If you are working in a perspective environment, your X & Y axis will be flipped when converting from screen space to world space. To fix this, multiply touchPos by negative one ( * -1). Ignore this for cameras in orthographic projection.
Source Code for joystickShoot.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class joystickShoot : MonoBehaviour { public Transform player; public float speed = 15.0f; public GameObject bulletPrefab; public Transform circle; public Transform outerCircle; private Vector2 startingPoint; private int leftTouch = 99; // Update is called once per frame void Update () { int i = 0; while(i < Input.touchCount){ Touch t = Input.GetTouch(i); Vector2 touchPos = getTouchPosition(t.position); // * -1 for perspective cameras if(t.phase == TouchPhase.Began){ if(t.position.x > Screen.width / 2){ shootBullet(); }else{ leftTouch = t.fingerId; startingPoint = touchPos; } }else if(t.phase == TouchPhase.Moved && leftTouch == t.fingerId){ Vector2 offset = touchPos - startingPoint; Vector2 direction = Vector2.ClampMagnitude(offset, 1.0f); moveCharacter(direction); circle.transform.position = new Vector2(outerCircle.transform.position.x + direction.x, outerCircle.transform.position.y + direction.y); }else if(t.phase == TouchPhase.Ended && leftTouch == t.fingerId){ leftTouch = 99;
circle.transform.position = new Vector2(outerCircle.transform.position.x, outerCircle.transform.position.y);} ++i; } } Vector2 getTouchPosition(Vector2 touchPosition){ return GetComponent<Camera>().ScreenToWorldPoint(new Vector3(touchPosition.x, touchPosition.y, transform.position.z)); } void moveCharacter(Vector2 direction){ player.Translate(direction * speed * Time.deltaTime); } void shootBullet(){ GameObject b = Instantiate(bulletPrefab) as GameObject; b.transform.position = player.transform.position; } }
Source Code for bullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class bullet : MonoBehaviour {
public float speed = 50.0f;
private Rigidbody2D rb;
private Vector2 screenBounds;
public GameObject explosion;
// Use this for initialization
void Start () {
rb = this.GetComponent<Rigidbody2D>();
rb.velocity = new Vector2(speed, 0);
screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
}
// Update is called once per frame
void Update () {
if(transform.position.x > screenBounds.x * -2){
Destroy(this.gameObject);
}
}
private void OnTriggerEnter2D(Collider2D other){
if(other.tag == "asteroid"){
GameObject e = Instantiate(explosion) as GameObject;
e.transform.position = transform.position;
Destroy(other.gameObject);
Destroy(this.gameObject);
}
}
}