Преобразование позиций и добавление постоянного значения оси ZC # - PullRequest
0 голосов
/ 03 сентября 2018

Я только начал работать над другим проектом, в котором одной из игровых механик является возможность перемещения дрона в положение курсора мыши.

Вот мой код ниже, где у меня есть несколько проблем (укажу)

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

public class lightDrone : MonoBehaviour
{
Vector3 newPosition;

void Start()
{
    newPosition = transform.position + (0,0,10); //***Problem A***
}
void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit))
        {
            newPosition = hit.point;
            transform.position = newPosition; // ***Problem B***
        }
    }
}
}

Проблема A - Я пытаюсь установить новую позицию = везде, где курсор нажимал + 10 по оси Y, поэтому кажется, что «Дрон» летит, а не в земле. Это ничего не дает и просто дает мне ошибки компиляции.

Я хочу, чтобы точная позиция была (cursor.x, (public int (y)), cursor.z), но у меня есть очень смутная идея сделать это.

Задача B -

В настоящее время, когда я щелкаю мышью, объект перемещается к курсору, но кажется, что он мгновенно телепортируется. Я хочу, чтобы он двигался с определенной скоростью, и я думаю, что мне нужен публичный float, чтобы сделать это и изменить transform.position на translate.position, но это опять-таки не работает.

Заранее спасибо за ответы на мои вопросы, я пытаюсь изучить эти новые механизмы и как их кодировать. :)

1 Ответ

0 голосов
/ 03 сентября 2018

Задача А

Если вы хотите, чтобы ваша новая позиция была там, где когда-либо нажимал курсор + 10 по оси Y, нет смысла помещать любой вашего кода в Start(). Это только для инициализации. Он запускается только один раз в начале сцены. Просто добавьте 10 к вашей новой позиции в методе Update().

Задача B

Установка для transform.position определенного значения заставит ваше преобразование мгновенно переместиться в эту позицию. Если вы хотите сделать это с течением времени, вам нужно перемещать ваше преобразование на несколько приращений за раз. Поскольку здесь вводится этот элемент «со временем», вам нужно использовать метод, который происходит со временем, поэтому вам нужны сопрограммы, асинхронные операции или вы можете использовать только метод обновления, если вы немного хитры.

Также вам нужно, чтобы луч пересекся и ударил что-то . Как плоская плоскость, земля, местность, что-нибудь с коллайдером. Если он нигде не попадет, у вас не будет нового места для перемещения.

Код

using UnityEngine;

public class LightDrone : MonoBehaviour
{
    public float speed = 60.0f;

    // Our destination needs to be remembered outside a single iteration of
    // Update. So we put it outside of the method in order to remember it
    // across multiple frames.
    private Vector3 currentDestination;

    // We need to check if we're at the destination yet so we know when to stop.
    private bool notAtDestinationYet;

    // When we're closer to the destination than this tolerance, we decide that
    // we have arrived there.
    private float tolerance = 0.1f;

    private void  Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                var newPosition = hit.point;
                // You can add whatever height you want here. I added
                // just 2 instead of 10.
                currentDestination = newPosition + new Vector3(0, 2.0f, 0);
                notAtDestinationYet = true;
            }
        }

        if (notAtDestinationYet)
        {
            // Use a bit of vector math to get the direction from our current
            // position to the destination. The direction is a normalized Vector
            // that we can just multiply with our speed to go in that direction
            // at that specific speed!

            var heading = currentDestination - transform.position;
            var distance = heading.magnitude;
            var direction = heading / distance;

            // Check if we've arrived at our destination.
            if (distance < tolerance)
            {
                notAtDestinationYet = false;
            }
            else
            {
                // If the remaining distance between us and the destination is
                // smaller than our speed, then we'll go further than necessary!
                // This is called overshoot. So we need to make our speed
                // smaller than the remaining distance.

                // We also multiply by deltaTime to account for the variable
                // amount of time that has passed since the last Update() call.
                // Without multiplying with the amount of time that has passed
                // our object's speed will increase or decrease when the
                // framerate changes! We really don't want that.

                float currentSpeed = Mathf.Clamp(speed * Time.deltaTime,
                    Mathf.Epsilon, distance);
                transform.position += direction * currentSpeed;
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...