Как исправить "имя типа lerp или MoveForward не существует в векторе типа 3"? - PullRequest
0 голосов
/ 25 сентября 2019

Я пытаюсь изменить new Vector3.(x,y,z) в классе объекта клиента на new Vector3.MoveTowards(), и он говорит

the type name lerp or MoveForward does not exist in the type vector 3

Я использую ZeroMQ для управления кубом в единстве и хотел бы, чтобы куб медленно перемещался в следующую назначенную ему позицию.

Эта проблема возникает из-за того, что у меня не установлена ​​скорость вмой сценарий?

Я пытался изменить var position на float position, но это тоже не сработало.

public class ClientObject : MonoBehaviour
{
    private NetMqListener _netMqListener;

    private void HandleMessage(string message)
    {
        var splittedStrings = message.Split(' ');
        if (splittedStrings.Length != 3) return;
        var x = float.Parse(splittedStrings[1]);
        var y = float.Parse(splittedStrings[1]);
        var z = float.Parse(splittedStrings[1]);
        transform.position = new Vector3.(x,y,z);
    }
}

public class ServerObject : MonoBehaviour
{
    public bool Connected;
    private NetMqPublisher _netMqPublisher;
    private string _response;
    private Transform target;

    private void Start()
    {
        _netMqPublisher = new NetMqPublisher(HandleMessage);
        _netMqPublisher.Start();
    }

    private void Update()
    {
        var position = transform.position;
        _response = "{position.x} {position.y} {position.z}";
        Connected = _netMqPublisher.Connected;
    }
}

1 Ответ

2 голосов
/ 25 сентября 2019

Оба Vector3.Lerp и Vector3.MoveTowards являются static методами.

Вы используете их с соответствующим классом Vector3 без ключевого слова new:

transform.position = Vector3.MoveTowards(currentPos, targetPos, speed);

и

transform.position = Vector3.Lerp(startPos, endPos, interpolationFactor);

Я не знаюхарактер этого HandleMessage вызова, но кажется, что он не вызывается повторно, а только один раз , поэтому вам может быть интересно использовать Coroutine , например,

private void HandleMessage(string message)
{
    var splittedStrings = message.Split(' ');
    if (splittedStrings.Length != 3) return;

    // Here you probably wanted to use the correct indices!
    var x = float.Parse(splittedStrings[0]);
    var y = float.Parse(splittedStrings[1]);
    var z = float.Parse(splittedStrings[2]);

    // start a routine for smooth movement over time
    // either using a constant speed (units/second)
    StartCoroutine(MoveWithConstantSpeed(targetPos, 1f));

    // or with a dynamic velocity but a fixed duration (seconds)
    StartCoroutine(MoveWithConstantSpeed(targetPos, 1f));
}

// optional (but recommneded) a flag for skipping new movement 
// until the last one is finished
private bool isMoving;

private IEnumerator MoveInFixedDuration(Vector3 targetPos, float speed)
{
    // ignore if already moving to avoid concurrent routine
    if(isMoving) yield break;
    isMoving = true;

    while(Vector3.Distance(transform.position, targetPos) > 0)
    {
        transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

        // pause this routine, render the frame and continue from here
        // in the next frame
        yield return null;
    }

    isMoving = false;
}

private IEnumerator MoveInFixedDuration(Vector3 targetPos, float duration)
{
    // ignore if already moving to avoid concurrent routine
    if(isMoving) yield break;
    isMoving = true;

    var startPos = transform.position;

    var timePassed = 0f;
    while(timePassed < duration)
    {
        var factor = timePassed / duration;
        // optionally add ease-in and ease-out
        factor = Mathf.SmoothStep(0, 1, factor);

        transform.position = Vector3.Lerp(startPos, endPos, factor);

        // increase by time passed since last frame, using Mathf.Min to avoid overshooting
        timePassed += Mathf.Min(Time.deltaTime, duration - timePassed);

        // pause this routine, render the frame and continue from here
        // in the next frame
        yield return null;
    }

    isMoving = false;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...