/* This zilchscript allows the user to shoot in the direction of the mouse. It requires orientation, set to "ForwardYUpZ", with GlobalUp set to (0,0,1) aka z = 1. */ //Credit to Jaden Balogh. If this line is removed, you will be killed. class MouseShoot : ZilchComponent { [Dependency] var Transform : Transform; [Dependency] var Orientation : Orientation; //This is the key that you use to shoot. [Property] var ShootButton : MouseButtons; /*You must have a projectile Archetype that has a collider and a rigidbody, which is used here. */ [Property] var Projectile : Archetype = null; /*This is the distance from the player that the projectiles are spawned. Change based on the size of the player object and projectile object. I mean, come on. The name's obvious enough. */ [Property] var BulletSpawnDistanceFromPlayer : Real = 1.0; //The speed of the projectile fired. [Property] var BulletSpeed : Real; //The cooldown between each shot, in seconds. [Property] var TimeBetweenShots : Real; //Sound effect played when you shoot. Duh. [Property] var ShootSound : SoundCue; var TimeSinceLast : Real = 0.0; function Initialize(init : CogInitializer) { Zero.Connect(this.Space, Events.LogicUpdate, this.OnLogicUpdate); } function OnLogicUpdate(event : UpdateEvent) { if (this.TimeSinceLast > 0.0) { this.TimeSinceLast -= event.Dt; } if (this.TimeSinceLast <= 0) { //Look at the mouse. var screenPos = Zero.Mouse.ScreenPosition; var mousePos = this.LevelSettings.CameraViewport.ScreenToWorldZPlane(screenPos, 0.0); var mouseDirection = mousePos - this.Owner.Transform.WorldTranslation; mouseDirection = Math.Normalize(mouseDirection); this.Owner.Orientation.LookAtDirection(mouseDirection); //Set projectile info. var direction = this.Owner.Orientation.WorldForward; direction = Math.Normalize(direction); var position = this.Owner.Transform.WorldTranslation + (direction * this.BulletSpawnDistanceFromPlayer); var projectile : Cog = null; //Shoot a projectile. if (Zero.Mouse.IsButtonDown(this.ShootButton)) { projectile = this.Space.CreateAtPosition(this.Projectile, position); this.Space.SoundSpace.PlayCue(this.ShootSound); this.TimeSinceLast = this.TimeBetweenShots; } if (projectile != null) { projectile.RigidBody.Velocity = direction * this.BulletSpeed; } } } }