将玩家平稳地推离物体

时间:2018-06-15 21:09:50

标签: c# unity3d

所以目前我的基本代码工作正常。当满足特定范围时,玩家会被推开。然而。这就像玩家在我正确的时候撞墙一样。

我该如何让它更顺畅?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlanetPush : MonoBehaviour {

    [SerializeField] Transform target;
    [SerializeField] float range = 1000;
    [SerializeField] float pushingspeed = 10f;

    // Update is called once per frame
    void Update ()
    {
        //Check if is in range
        if (Vector3.Distance(target.position, transform.position) < range)
        { 
            Debug.DrawLine(transform.position, target.position, Color.green);

            //Push away from object
            target.position = Vector3.MoveTowards(target.position, transform.position, Time.deltaTime * -pushingspeed);
        }
        else
        {
            Debug.DrawLine(transform.position, target.position, Color.yellow);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

实际上很容易。我不得不提高推进速度等于我的最大玩家速度。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlanetPush : MonoBehaviour {

    [SerializeField] Transform target;
    [SerializeField] float range = 1000;
    [SerializeField] float pushingspeed = 0.01f;
    [SerializeField] float DampSpeed = 0.1f;
    float MaxPlayerSpeed = 30f;

    // Update is called once per frame
    void Update ()
    {
        //Check if is in range
        if (Vector3.Distance(target.position, transform.position) < range)
        { 
            Debug.DrawLine(transform.position, target.position, Color.green);
            pushingspeed += DampSpeed;
            if (pushingspeed >= MaxPlayerSpeed)
            {
                pushingspeed = MaxPlayerSpeed;
            }
            //Push away from object
            target.position = Vector3.MoveTowards(target.position, transform.position, Time.deltaTime * -pushingspeed);
        }
        else
        {
            Debug.DrawLine(transform.position, target.position, Color.yellow);
            pushingspeed = 0.1f;
        }
    }
}