2D Rigidbody с движением Touchscript в Unity не останется в границах - PullRequest
0 голосов
/ 16 октября 2019

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

Проблема в том, что весла не будут сталкиваться с окружающими коллайдерами, которые я установил на камере. , используя следующий скрипт:

 using UnityEngine;
 using System.Collections;

  namespace UnityLibrary
     {
      public class EdgeCollider : MonoBehaviour 
      {

    public float colDepth = 4f;
    public float zPosition = 0f;
    private Vector2 screenSize;
    private Transform topCollider;
    private Transform bottomCollider;

    private Transform leftCollider;
    private Transform rightCollider;
    private Vector3 cameraPos;
    // Use this for initialization
    void Start () {
    //Generate our empty objects
        topCollider = new GameObject().transform;
        bottomCollider = new GameObject().transform;
        rightCollider = new GameObject().transform;
        leftCollider = new GameObject().transform;

    //Name our objects 
        topCollider.name = "TopCollider";
        bottomCollider.name = "BottomCollider";
        rightCollider.name = "RightCollider";
        leftCollider.name = "LeftCollider";

    //Add the colliders
        topCollider.gameObject.AddComponent<BoxCollider2D>();
        bottomCollider.gameObject.AddComponent<BoxCollider2D>();
        rightCollider.gameObject.AddComponent<BoxCollider2D>();
        leftCollider.gameObject.AddComponent<BoxCollider2D>();

    //Make them the child of whatever object this script is on, preferably on the Camera so the objects move with the camera without extra scripting
        topCollider.parent = transform;
        bottomCollider.parent = transform;
        rightCollider.parent = transform;
        leftCollider.parent = transform;

    //Generate world space point information for position and scale calculations
        cameraPos = Camera.main.transform.position;
        screenSize.x = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
        screenSize.y = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;

    //Change our scale and positions to match the edges of the screen...   
        rightCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
        rightCollider.position = new Vector3(cameraPos.x + screenSize.x + (rightCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
        leftCollider.localScale = new Vector3(colDepth, screenSize.y * 2, colDepth);
        leftCollider.position = new Vector3(cameraPos.x - screenSize.x - (leftCollider.localScale.x * 0.5f), cameraPos.y, zPosition);
        topCollider.localScale = new Vector3(screenSize.x * 2, colDepth, colDepth);
        topCollider.position = new Vector3(cameraPos.x, cameraPos.y + screenSize.y + (topCollider.localScale.y * 0.5f), zPosition);
        bottomCollider.localScale = new Vector3(screenSize.x * 2, colDepth, colDepth);
        bottomCollider.position = new Vector3(cameraPos.x, cameraPos.y - screenSize.y - (bottomCollider.localScale.y * 0.5f), zPosition);
    }
    }
    }

Мяч сталкивается с лопастями и отскакивает, как и должно, а также сталкивается с окружающими коллайдерами и отскакивает идеально. Тем не менее, лопасти движутся прямо через окружающие коллайдеры (EdgeColliders). Обратите внимание, что я использую пакет Touchscript из хранилища активов для управления движением. Он не двигает твердое тело, он использует преобразование. Следует также отметить, что когда я делаю весла очень легкими (масса 0,0001) и добавляю к ним гравитацию, они сталкиваются с краевыми коллайдерами и не проходят сквозь экран.

1 Ответ

0 голосов
/ 16 октября 2019

Если вы хотите, чтобы весло сталкивалось с окружающим боксом, вам следует переместить Rigidbody с помощью AddForce (), а не перемещать преобразование. Или вы можете ограничить движение лопастей следующим образом:

if (transform.position.x < LeftScreenEdge)
{
    transform.position = new Vector3(LeftScreenEdge, transform.position.y);        
}
...