/// <summary> /// Handle ComponentCreated events. /// </summary> /// <param name="evt"> /// The <see cref="IEvent"/> event to handle. /// </param> private void OnComponentCreated(IEvent evt) { if (evt.EventData is PlayerComponent) { PlayerComponent data = (PlayerComponent)evt.EventData; Debug.Log("Setting lives for player " + data.EntityId); data.Lives = this.DefaultLives; data.Score = 0; } }
/// <summary> /// Handle SpawnBallsForPlayer events. /// </summary> /// <param name="evt"> /// The <see cref="IEvent"/> event to handle. /// </param> private void OnSpawnBallsForPlayer(IEvent evt) { PlayerComponent player = (PlayerComponent)evt.EventData; if (!this.Game.ComponentSystem.TryGetComponent(player.EntityId, out player)) { return; } Debug.Log("Spawning balls for player " + player.EntityId); player.Lives--; Transform ballTransform; Transform paddleTransform; Vector3 paddleUpVector; BallComponent ball; int ballId; foreach (PaddleComponent paddle in this.Game.ComponentSystem.Components <PaddleComponent>()) { if ((paddle == null) || (paddle.PlayerId != player.EntityId)) { continue; } // Instanciate the prefab and position it in the paddle GameObject ballObject = (GameObject)GameObject.Instantiate(this.BallPrefab); ballTransform = ballObject.transform; paddleTransform = paddle.gameObject.transform; ballTransform.parent = paddleTransform.parent; ballTransform.position = paddleTransform.position; // Move the ball on top of the paddle by using the y extent of // its collider and that of the paddle, rotated by the paddles // rotation, blindly assuming, the collider has an offset of (0, 0, 0). paddleUpVector = new Vector3(0.0f, ballObject.collider.bounds.extents.y, 0.0f); paddleUpVector += new Vector3(0.0f, paddle.gameObject.collider.bounds.extents.y, 0.0f); paddleUpVector = paddleTransform.rotation * paddleUpVector; // Make the vector a bit larger, so there isn't an // immediate collision with the paddle. Cheap hack. paddleUpVector *= 1.001f; ballTransform.position += paddleUpVector; // Set the velocity of the ball by rotating its default velocity // by the rotation of the paddle. It will start to move as soon // as the game continues. ball = ballObject.GetComponent <BallComponent>(); ball.Velocity = paddleTransform.rotation * ball.DefaultVelocity; // And finally, assign an ID to all components. This assumes, that // the ball is a simple object, without any children. ballId = this.Game.ComponentSystem.GetUniqueEntityId(); foreach (Component unityComponent in ballObject.GetComponents(typeof(Component))) { if (unityComponent is IComponent) { ((IComponent)unityComponent).EntityId = ballId; this.Game.EventManager.QueueEvent(new HelGamesEvent(ComponentSystemEvents.ComponentCreated, unityComponent)); } } } }