So basically I am trying to make a archer and want the arrow to start from archer and go anywhere the user clicks.
So like archer is standing in the bottom left corner of screen and I want a arrow to be initiated at his position and go to the place wherever user clicks with mouse or touch on the screen. I have a arrow prefab.
I am attaching this script to the archer. But there is some issue with the coordinate system …
Please help/
----------``
using UnityEngine;
using System.Collections;
public class FireArrow : MonoBehaviour
{
public float speed = 1F;
public GameObject arrow;
GameObject go;
bool moveArrow;
// Use this for initialization
void Start()
{
moveArrow = false;
}
// Update is called once per frame
void Update()
{
Vector3 worldPos = new Vector3(0, 0);
if (Input.GetMouseButtonUp(0))
{
Debug.Log("Pressed left click.");
Vector3 mousePos = Input.mousePosition;
mousePos.z = 0.0f;
worldPos = (mousePos);
go = GameObject.Instantiate(arrow,transform.position, Quaternion.identity) as GameObject;
moveArrow = true;
}
if (moveArrow)
{
if (go.transform.position != worldPos)
{
go.transform.position =(worldPos);
}
}}
}
I’m doing something like that at the moment. I move the arrow with script attached to arrow itself, so I can shoot another arrow before the previous arrow has reached its target. Maybe this works for you too. I originally used to shoot arrows towards the direction I clicked but these scripts shoot the arrow exactly to the point you clicked. Also added a timer between shots. With touch devices this script shot about ten arrows whit quick tap on the screen without the timer.
I use this script on my weapon:
using UnityEngine;
using System.Collections;
public class FireArrow : MonoBehaviour
{
public GameObject arrow;
public float shootTimer = 1;
public float timeBetweenShots = 1;
void Update ()
{
shootTimer += Time.deltaTime;
if (Input.GetMouseButtonDown(0) && shootTimer >= timeBetweenShots)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
{
GameObject instantiatedArrow;
instantiatedArrow = Instantiate(arrow, transform.position, Quaternion.identity) as GameObject;
ArrowScript arrowScript;
arrowScript = instantiatedArrow.gameObject.GetComponent<ArrowScript>();
arrowScript.target = hit.point;
shootTimer = 0;
}
}
}
}
And this on my arrow prefab:
using UnityEngine;
using System.Collections;
public class ArrowScript : MonoBehaviour
{
public Vector3 target;
public float speed;
void Update ()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target, step);
}
}