- Home /
Moving Object using Raycast / Lerp C# 2D
Hi there,
I have the following script which doesn't seem to be working correctly, it should be moving the object from the player to the end of the ray.
It is not doing this, I have added in the debug to see where it is falling down, and it is never calling the 2nd debug so this is why it isn't moving the object, I cannot figure out why I can see the ray but the object will not move along the ray?
any help would be greatly appreciated, many thanks,
public Transform spawn;
public GameObject Hand;
public GameObject projectile;
public float shotdistance;
public float speed;
private float lerpValue = 0;
private Vector3 startPosition;
private bool isMoving;
void OnCollisionStay2D (Collision2D coll)
{
if (Input.GetKeyDown (KeyCode.E)) {
if (coll.gameObject.tag == "Pickup") {
if (Hand.transform.childCount < 1) {
coll.gameObject.transform.position = Hand.transform.position;
coll.gameObject.transform.parent = Hand.transform;
projectile = coll.gameObject;
//coll.gameObject.name = "Projectile";
}
}
}
}
void Update ()
{
if (Input.GetMouseButtonUp (1))
{
if (Hand.transform.childCount == 1)
{
lerpValue = 0;
startPosition = projectile.transform.position;
projectile.gameObject.transform.parent = null;
Ray ray = new Ray(spawn.position,spawn.up);
RaycastHit hit;
float shotDistance = shotdistance;
Debug.DrawRay(spawn.position,spawn.up * shotDistance);
if (Physics.Raycast(ray,out hit, shotDistance) && !isMoving)
{
isMoving = true;
shotDistance = hit.distance;
//speed = distance / time
//therefore: time = distance / speed
float time = shotDistance / speed;
Debug.DrawRay(ray.origin,ray.direction * shotDistance,Color.red,time);
StartCoroutine(ProjectileMotion(hit.point, time));
}
}
}
}
IEnumerator ProjectileMotion(Vector3 endPosition, float time)
{
while(lerpValue < time)
{
lerpValue += Time.deltaTime;
projectile.gameObject.transform.position = Vector3.Lerp(startPosition, endPosition, lerpValue / time);
yield return null;
}
isMoving = false; //&& !isMoving
}
}
Comment
Your answer
Follow this Question
Related Questions
Raycast - arrow stopped by walls (layer) but not by units (layer) 1 Answer
NPC sight by collider 0 Answers
Lerp not moving 2D object correctly 1 Answer
Raycast2D Layermasks and incomplete docs 1 Answer
Issue with raycasting in 2D 1 Answer