I have a sprite that rotates based on holding a mouse button. So once the left mouse button is released he shoots an arrow. The rotation of the arrow is good. ( maybe it misses couple of degrees but its fine ) . But here is the problem i have an AddForce function and that Add Force function needs to shoot based on rotation of the Arrow. Keep in mind that i want my arrow to have a real curved flying. Here is the code.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(PlayerController))]
public class ArrowControl : MonoBehaviour {
public float thrust = 250f;
private Rigidbody2D arrow;
// Use this for initializatio
private bool flight;
void Start () {
arrow = GetComponent<Rigidbody2D> ();
flight = true;
}
// Update is called once per frame
void Update () {
ArrowMotion ();
}
void ArrowMotion(){
if (Input.GetMouseButtonUp(0)){
flight = true;
if(flight){
arrow.AddForce(Vector2.right * thrust);
flight = false;
}
}
}
}
And the second script
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour {
//Public Vars
[SerializeField]
public Camera camera;
[SerializeField]
public Rigidbody2D arrow;
public bool shoot;
public Vector3 mousePosition;
public PlayerController play;
//Private Vars
private Vector3 direction;
private float distanceFromObject;
private Rigidbody2D rigidbody;
private bool isAiming;
private Animator anim;
void Start() {
rigidbody = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
shoot = false;
}
void FixedUpdate() {
HandleRotation ();
}
void Update(){
HandleShoot();
}
void HandleRotation(){
if (Input.GetMouseButton(0)){
isAiming = true;
//Grab the current mouse position on the screen
/*mousePosition = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y, Input.mousePosition.z + camera.transform.position.z));
//Rotates toward the mouse
rigidbody.transform.eulerAngles = - new Vector3(0,0,Mathf.Atan2((mousePosition.y - transform.position.y), (mousePosition.x - transform.position.x))*Mathf.Rad2Deg + 180); */
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 dir = Input.mousePosition - pos;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
void HandleShoot()
{
if (isAiming) {
anim.SetBool("Aiming", true);
}
if (Input.GetMouseButtonUp (0)) {
isAiming = false;
anim.SetBool ("Aiming", false);
shoot = true;
if (shoot) {
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
Vector3 dir = Input.mousePosition - pos;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Instantiate (arrow, rigidbody.position, transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward));
shoot = false;
}
}
}
}