Связанное перетаскивание объектов из коробки в коробку - PullRequest
0 голосов
/ 29 декабря 2018

Комната, содержащая сферу и куб

Привет,

В рамках моего проекта у меня есть сфера и куб в коробке.Куб перетаскивается пользователем с помощью мыши.Сфера перемещается к случайным координатам внутри рамки.В течение долгого времени я изо всех сил пытался выяснить, как связать оба объекта с коробкой, которая состоит из 6 прямоугольных призм (по одной на каждую стену + крышу + пол).

Не могли бы вы все помочь мне разобраться, как это сделать?

Код, используемый для управления сферой и кубом, размещен ниже.

Сфера

using System.Collections;
using System.IO;

using UnityEngine;

public class PlayerController : MonoBehaviour
{
private float movementDuration = 2.0f;
private WaitForSeconds waitBeforeMoving = new WaitForSeconds(2f);
private Vector3[] path = new Vector3[20];
private string filepath = null;

private void Start()
{
    StartCoroutine(MainRoutine());
    filepath = Application.dataPath + "/Player.txt";
    File.WriteAllText(filepath, "The player blob visited these random coordinates: \n\n");
}

private IEnumerator MainRoutine()
{
    //generate new path:
    for (int i = 0; i < path.Length; i++)
    {
        float timer = 0.0f;
        Vector3 startPos = transform.position;
        float x = RandomNum(timer);
        float y = RandomNum(x);
        float z = RandomNum(y);
        path[i] = new Vector3(x, y, z);
    }

    //traverse path:
    for (int i = 0; i < path.Length; i++)
    {
        float timer = 0.0f;
        Vector3 startPos = transform.position;
        while (timer < movementDuration)
        {
            timer += Time.deltaTime;
            float t = timer / movementDuration;
            //t = t * t * t * (t * (6f * t - 15f) + 10f);
            transform.position = Vector3.Lerp(startPos, path[i], t);
            yield return null;
        }
        yield return waitBeforeMoving;
    }

    //print path:
    PrintPoints();
}

private void PrintPoints()
{

    foreach (Vector3 vector in path)
    {
        File.AppendAllText(filepath, string.Format("{0}\n\n", JsonUtility.ToJson(vector)));
    }
}

private float RandomNum(float lastRandNum)
{
    //Random value range can be changed in the future if necessary
    float randNum = Random.Range(-30.0f, 30.0f);
    return System.Math.Abs(randNum - lastRandNum) < float.Epsilon ? RandomNum(randNum) : randNum;
}

}

Куб

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

[RequireComponent(typeof(MeshCollider))]


public class UserController : MonoBehaviour
{
private Vector3 Dist;
private float PosX = 0.0f;
private float PosY = 0.0f;
private float PosZ = 0.0f;
private bool shiftOn = false;

private void OnMouseDown()
{

        Dist = Camera.main.WorldToScreenPoint(transform.position);
        PosX = Input.mousePosition.x - Dist.x;
        PosY = Input.mousePosition.y - Dist.y;
        PosZ = Input.mousePosition.z - Dist.z;

}
private void OnMouseDrag()
{

    if (Input.GetMouseButton(0))
    {
        if (shiftOn)
        {
            //3D Drag, courtesy of Unity Forums
            //float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
            transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x - PosX, Input.mousePosition.y - PosY, Input.mousePosition.z - PosZ));
        }

        else
        {
            //Plane Drag
            //float distance_to_screen = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
            Vector3 pos_move = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x - PosX, Input.mousePosition.y - PosY, Input.mousePosition.z - PosZ));
            transform.position = new Vector3(pos_move.x, transform.position.y, pos_move.z);
        }



    }

}



// Update is called once per frame
private void Update()
{

    if (Input.GetKeyDown(KeyCode.LeftShift)||Input.GetKeyDown(KeyCode.RightShift))
    {
        Debug.Log("Shift Pressed"); //Logs message to the Unity Console.
        shiftOn = true;
    }

    if (Input.GetKeyUp(KeyCode.LeftShift) || Input.GetKeyUp(KeyCode.RightShift))
    {
        Debug.Log("Shift Released"); //Logs message to the Unity Console.
        shiftOn = false;
    }



}



}
...