使用c#沿着光线投影移动对象

时间:2014-07-31 19:16:49

标签: c# unity3d raycasting

我想逐渐沿着光线移动物体,

到目前为止,我有以下代码将它移动到目的地而不是在那里顺利滑动。

如果我从末尾移除了Destroy(projectile.rigidbody2D)线,那么它会不会在所有地方反弹?

非常感谢任何帮助!

    void Update () 
{

            if (Input.GetMouseButtonUp (1)) {
            if (Hand.transform.childCount == 1){
            projectile.gameObject.transform.parent = null;

            Ray ray = new Ray(spawn.position,spawn.up);
            RaycastHit hit;

            float shotDistance = shotdistance;

            if (Physics.Raycast(ray,out hit, shotDistance)) {
                shotDistance = hit.distance;
            }
            projectile.AddComponent<Rigidbody2D>();
            projectile.rigidbody2D.gravityScale = 0;
            projectile.rigidbody2D.AddForce(Vector2.up * 5);
            projectile.transform.position = Vector3.MoveTowards(projectile.transform.position,ray.direction * shotDistance,shotDistance);
            Debug.DrawRay(ray.origin,ray.direction * shotDistance,Color.red,1);
            Destroy(projectile.rigidbody2D);

                            }
                    }
            }

1 个答案:

答案 0 :(得分:0)

private float lerpValue = 0;
public float speed;
private Vector3 startPosition;

private bool isMoving;

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;

            if (Physics.Raycast(ray,out hit, shotDistance) && !isMoving)
            {
    isMoving = true;
                shotDistance = hit.distance;
                //speed = distance / time
                //therefore: time = distance / speed
                float time = shotDistance / speed;

                StartCoroutine(ProjectileMotion(hit.point, time));
            }
        }
    }
}

IEnumerator ProjectileMotion(Vector3 endPosition, float time)
{
    while(lerpValue < time)
    {
        lerpValue += Time.deltaTime;
        projectile.transform.position = Vector3.Lerp(startPosition, endPosition, lerpValue / time);
    }
isMoving = false;
}