AtariPongBall.cs 2.2 KB

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