Мяч не отскакивает от экрана - PullRequest
0 голосов
/ 19 октября 2019

Во-первых, я извиняюсь за мой английский. Надеюсь, я смогу объяснить это правильно. В моей игре мяч должен отскакивать от края до края. Из видео у меня есть код с мячом в поле, должен остаться, однако мяч теперь подпрыгивает и скользит по экрану

Я пробовал утверждение if, но я новичок и незнать, правильно ли я понял

public class Ball_Controller : MonoBehaviour

{[SerializeField] private float moveSpeed ​​= 10f;

[SerializeField] private Vector2 startDirection;

[SerializeField] private Vector2 startOtherDirection;

private Rigidbody2D rb;

public static bool GameIsover;
public GameObject gameOverUI;


public Transform topLeft;
public Transform bottomRight;





private void Start()
{



    GameIsover = false;

}
void Update()
{
    BallMove();


    transform.position = new Vector3(Mathf.Clamp(transform.position.x, topLeft.position.x, bottomRight.position.x), Mathf.Clamp(transform.position.y, bottomRight.position.y, topLeft.position.y), transform.position.z);
    if (transform.position.y == Screen.height || transform.position.x == Screen.width)
    {

        BallMoveOther();
    }





    if (GameIsover)
        return;

    if (Input.GetKeyDown("e"))
    {
        EndGame();


    }



}



void EndGame()
{

    Debug.Log("Game Over");
    GameIsover = true;
    gameOverUI.SetActive(true);
    Time.timeScale = 0;


}



private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag.Equals ("Player"))
    {

        Destroy(collision.gameObject);
        Destroy(gameObject);
        EndGame();
    }




}

private void BallMove()
{
    rb = GetComponent<Rigidbody2D>();

    rb.velocity = moveSpeed * startDirection;
}
private void BallMoveOther()
{
    rb = GetComponent<Rigidbody2D>();
    rb.velocity = moveSpeed * startOtherDirection;
}

}

1 Ответ

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

Проблема с кодом ниже:

transform.position = new Vector3(Mathf.Clamp(transform.position.x, topLeft.position.x, bottomRight.position.x), Mathf.Clamp(transform.position.y, bottomRight.position.y, 
topLeft.position.y), transform.position.z);

if (transform.position.y == Screen.height || transform.position.x == Screen.width){
    BallMoveOther();
}
  1. Избегайте использования отдельных объектов для нахождения границ экрана
  2. В операторе if transform.position.y - это глобальная позиция, а screen.height - нет.

Попробуйте что-то вроде этого:

// Converting Screen positions to world space
Vector3 screenStart = Camera.main.ScreentoWorldPoint(new Vector3(0,0,0));
Vector3 screenEnd = Camera.main.ScreentoWorldPoint(new Vector3(screen.width,screen.height,0));

// Clampping the sprite within the screen
transform.position = new Vector3(
    Mathf.Clamp(transform.position.x,screenStart.position.x,screenEnd.position.x),
    Mathf.Clamp(transform.position.y,screenStart.position.y,screenEnd.position.y),
    transform.position.z);
// Getting the length and width of the sprite
Vector2 SpriteBnds = transform.GetComponent<SpriteRenderer>().bounds.size;

// checking if the sprite went beyond the screen bounds in any four directions
if(
    transform.position.y+(SpriteBnds.y/2) >=screenEnd.position.y ||
    transform.position.y - (SpriteBnds.y/2) <= screenstart.position.y ||
    transform.position.x+(SpriteBnds.x/2) >=screenEnd.position.x ||
    transform.position.x - (SpriteBnds.x/2) <= screenstart.position.x)
    {
        BallMoveOther();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...