001package com.fs.starfarer.api.impl.campaign.ghosts;
002
003import org.lwjgl.util.vector.Vector2f;
004
005import com.fs.starfarer.api.EveryFrameScript;
006import com.fs.starfarer.api.campaign.CampaignFleetAPI;
007import com.fs.starfarer.api.campaign.SectorEntityToken;
008import com.fs.starfarer.api.util.Misc;
009
010public class SpeedReduction implements EveryFrameScript {
011
012        protected float elapsed;
013        protected SectorEntityToken target;
014        protected float speedReductionRate;
015        protected float durationSeconds;
016
017        public SpeedReduction(SectorEntityToken target, float speedReductionFraction) {
018                this(target, speedReductionFraction, 0.2f);
019        }
020        public SpeedReduction(SectorEntityToken target, float speedReductionFraction, float durationSeconds) {
021                this.target = target;
022                this.durationSeconds = durationSeconds;
023                speedReductionRate = target.getVelocity().length() * speedReductionFraction / durationSeconds;
024        }
025
026        public void advance(float amount) {
027                if (target instanceof CampaignFleetAPI) {
028                        target.setOrbit(null);
029                }
030                
031                Vector2f v = target.getVelocity();
032                
033                Vector2f dV = Misc.getUnitVector(new Vector2f(), v);
034                dV.scale(-1f * Math.min(v.length(), speedReductionRate * Math.min(durationSeconds, amount)));
035                
036                SensorGhost ghost = SensorGhostManager.getGhostFor(target);
037                if (ghost != null) {
038                        v = ghost.getMovement().getVelocity();
039                        ghost.getMovement().getVelocity().set(v.x + dV.x, v.y + dV.y);
040                } else if (target instanceof CampaignFleetAPI) {
041                        v = ((CampaignFleetAPI)target).getVelocityFromMovementModule(); 
042                        ((CampaignFleetAPI)target).setVelocity(v.x + dV.x, v.y + dV.y);
043                } else {
044                        target.getVelocity().set(v.x + dV.x, v.y + dV.y);
045                }
046
047                elapsed += amount;
048        }
049
050        public boolean isDone() {
051                return elapsed >= durationSeconds;
052        }
053
054        public boolean runWhilePaused() {
055                return false;
056        }
057
058}