Ball.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using UnityEngine;
  2. namespace Mirror.Examples.Pong
  3. {
  4. public class Ball : NetworkBehaviour
  5. {
  6. public float speed = 30;
  7. public Rigidbody2D rigidbody2d;
  8. public override void OnStartServer()
  9. {
  10. base.OnStartServer();
  11. // only simulate ball physics on server
  12. rigidbody2d.simulated = true;
  13. // Serve the ball from left player
  14. rigidbody2d.velocity = Vector2.right * speed;
  15. }
  16. float HitFactor(Vector2 ballPos, Vector2 racketPos, float racketHeight)
  17. {
  18. // ascii art:
  19. // || 1 <- at the top of the racket
  20. // ||
  21. // || 0 <- at the middle of the racket
  22. // ||
  23. // || -1 <- at the bottom of the racket
  24. return (ballPos.y - racketPos.y) / racketHeight;
  25. }
  26. // only call this on server
  27. [ServerCallback]
  28. void OnCollisionEnter2D(Collision2D col)
  29. {
  30. // Note: 'col' holds the collision information. If the
  31. // Ball collided with a racket, then:
  32. // col.gameObject is the racket
  33. // col.transform.position is the racket's position
  34. // col.collider is the racket's collider
  35. // did we hit a racket? then we need to calculate the hit factor
  36. if (col.transform.GetComponent<Player>())
  37. {
  38. // Calculate y direction via hit Factor
  39. float y = HitFactor(transform.position,
  40. col.transform.position,
  41. col.collider.bounds.size.y);
  42. // Calculate x direction via opposite collision
  43. float x = col.relativeVelocity.x > 0 ? 1 : -1;
  44. // Calculate direction, make length=1 via .normalized
  45. Vector2 dir = new Vector2(x, y).normalized;
  46. // Set Velocity with dir * speed
  47. rigidbody2d.velocity = dir * speed;
  48. }
  49. }
  50. }
  51. }