The code below is not working quite like I want it to. If you look for the comment below that says
//NOT QUITE WORKING. What I WANT to do is when I click on a spot on the screen, I want my item to move toward that spot on the screen (over time, not just appearing) NOT STOPPING WHEN IT GETS THERE. Just keep moving. Until the if block is reached. What is happening now is that wherever I click on the screen, the item goes there, but just stops and hence my if block is never hit and the item never returns to the player unless I manually move the player away. How can I get the gameobject
to move over time in the direction I clicked, not stopping at the spot I clicked? Thanks in advance
using UnityEngine;
using System.Collections;
public class ThrowSword : MonoBehaviour {
private GameObject thrownItem;
private GameObject weaponMount;
private Vector3 swordForce = new Vector3(-250, 200, -500);
private float swordDistance = 0.0f;
private Vector3 hitPosition;
public float returnfactor=0.1f;
private bool isThrowing = false;
private Vector3 startPos;
public float swordSpeed = 5.0f;
public float maxdistance = 20.0f;
public bool throwSword = false, hitSomething = false;
public Vector3 throwDirection = new Vector3();
void OnTriggerEnter(Collider collision)
{
//prevent sword reset when colliding with main player
if (collision.gameObject.name != "Thor" collision.gameObject.name != "ThorBody")
{
hitSomething = true;
}
}
void Awake()
{
thrownItem = GameObject.Find("sword_01_prefab");
weaponMount = GameObject.Find("WeaponMount");
isThrowing = false;
}
public void initiateThrow()
{
startPos = thrownItem.transform.localPosition;
throwSword = true;
hitSomething = false;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (throwSword)
{
//record current max distance
swordDistance = Vector3.Distance(thrownItem.transform.position, weaponMount.transform.position);
thrownItem.transform.localRotation = new Quaternion(0.0f, 0.0f, -90.0f, 0.0f);
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray,out hit,1000))
{
throwDirection = hit.point;
}
if (isThrowing == false)
{
isThrowing = true;
thrownItem.transform.parent = null;
//NOT QUITE WORKING
thrownItem.transform.position = Vector3.Lerp(thrownItem.transform.position, throwDirection, Time.deltaTime * swordSpeed);
}
//if max distance reached
if ((swordDistance >= maxdistance) || hitSomething)
{
StartCoroutine(resetSword());
}
}
}
IEnumerator resetSword()
{
yield return new WaitForSeconds(1.0f);
//reset variables tween
throwSword = false;
isThrowing = false;
hitSomething = false;
swordDistance = 0.0f;
//return to weapon mount
thrownItem.transform.position = Vector3.Lerp(thrownItem.transform.position, weaponMount.transform.position, returnfactor);
thrownItem.transform.rotation = weaponMount.transform.rotation;
thrownItem.transform.parent = weaponMount.transform;
}
}