protected void ProcessInput(float delta) //this is where all the AI happens { Transform camXform = GlobalTransform; dir = new Vector3(); float distanceToPoint = Translation.DistanceTo(pathPos); float distanceToPlayer = Translation.DistanceTo(nav.GetClosestPoint(player.Translation)); if (distanceToPoint > 0.5f && distanceToPlayer > rangeThreshold) { //GD.Print("outside range"); currentMode = longRangeMode; } else { //GD.Print("within range"); currentMode = closeRangeMode; } if (currentMode != PathMode.DEFENDER) { LookAt(new Vector3(pathPos.x, Translation.y, pathPos.z), Vector3.Up); } //this line exists to rotate enemy wheels if it has any. I should find a way to interpolate the rotation to make the animation more natural. inputMovementVector = inputMovementVector.Normalized(); dir += -camXform.basis.z.Normalized() * inputMovementVector.y; dir += camXform.basis.x.Normalized() * inputMovementVector.x; }
public void Update(IEnumerable <Actions> actions, float deltaTime) { Vector2 direction = Vector2.Zero; if (actions.Contains(Actions.Up)) { direction.Y += 1; } if (actions.Contains(Actions.Down)) { direction.Y -= 1; } if (actions.Contains(Actions.Right)) { direction.X += 1; } if (actions.Contains(Actions.Left)) { direction.X -= 1; } if (direction != Vector2.Zero) { Position += direction.Normalized() * _speed * deltaTime; } }
private void HandleCollision(CollisionInfo info) { // Bounce and reposition beyond collision area switch (info.Direction) { case Collision.Direction.Left: _velocity.X = -_velocity.X; Position.X = info.Coordinate; break; case Collision.Direction.Right: _velocity.X = -_velocity.X; Position.X = info.Coordinate - Size.X; break; case Collision.Direction.Top: _velocity.Y = -_velocity.Y; Position.Y = info.Coordinate; break; case Collision.Direction.Bottom: _velocity.Y = -_velocity.Y; Position.Y = info.Coordinate - Size.Y; break; } // If collided with paddle, set velocity based on position of ball relative to paddle if (info.SourceEntity is Paddle paddle) { var bounceVector = (BoundingBox.Center - paddle.BoundingBox.Center).ToVector2().Normalized(); _velocity = (_velocity.Normalized() + bounceVector).Normalized() * _speed; } }
public override void AI() { if (projectile.timeLeft == Lifespan) //First tick { projectile.rotation = projectile.velocity.ToRotation() + 45.ToRadians(); //45 degrees because of the sprite int dustAmount = 16; for (int i = 0; i < dustAmount; i++) //We create 16 dusts in an ellipse { Vector2 rotation = Vector2.UnitY.RotatedBy(FullCircle * i / dustAmount); //A circle of radius 1 is divided into the set amount of points, focusing on the current point in the loop rotation *= new Vector2(1, 4); // Multiplies the points by a vertical squish factor so the circle becomes an ellipse rotation = rotation.RotatedBy(projectile.velocity.ToRotation()); //Rotates the resulting ellipse to align with the projectile's rotation Dust newDust = Dust.NewDustDirect(projectile.Center + rotation, 0, 0, /*Type*/ 180, 0f, 0f, /*Alpha*/ 0, default(Color), /*Scale*/ 1.5f); newDust.velocity = rotation.Normalized(); //Shoots outwards newDust.noGravity = true; } } if (HasHitEnemy) //Is stuck to an enemy { if (!Target.active) { projectile.Kill(); //Kills the projectile if the target is dead } Target.GetGlobalNPC <VirtuousNPC>().summonedSwordStuck++; //Applies the damage-over-time effect to the target projectile.Center = Target.Center - relativeCenter.RotatedBy(Target.rotation - originalTargetRotation); //Moves the projectile to the fixed position around the target, relative to where it originally hit projectile.rotation = originalProjRotation - originalTargetRotation + Target.rotation; //Rotates the sprite accordingly projectile.position -= projectile.velocity; //Stops velocity from affecting the projectile normally } Lighting.AddLight(projectile.Center, 0.0f, 0.5f, 0.6f); }
Vector2 align(List <IndividualParticle> neighbors) { Vector2 sum = new Vector2(0, 0); int count = 0; foreach (IndividualParticle particle in neighbors) { float distanceTo = Position.DistanceTo(particle.Position); if (distanceTo > 0 && distanceTo < neighborDistance) { sum += particle.velocity; count++; } } if (count > 0) { sum /= (float)count; sum = sum.Normalized(); sum *= maxSpeed; Vector2 steer = sum - velocity; steer = steer.Clamped(maxForce); return(steer); } return(new Vector2(0, 0)); }
Vector2 avoid(List <Obstacle> obstacles) { Vector2 viewAhead = Position + velocity.Normalized() * seeAheadDistance; Vector2 viewAhead2 = viewAhead * 0.5f; Vector2 avoidanceForce = new Vector2(0, 0); Obstacle closest = null; foreach (Obstacle o in obstacles) { if (viewAhead.DistanceTo(o.Position) <= o.radius || viewAhead2.DistanceTo(o.Position) <= o.radius) { if (closest == null) { closest = o; } else if (Position.DistanceTo(o.Position) < Position.DistanceTo(closest.Position)) { closest = o; } } } if (closest != null) { avoidanceForce = viewAhead - closest.Position; avoidanceForce = avoidanceForce.Normalized(); avoidanceForce *= maxAvoidForce; } return(avoidanceForce); }
// // Called every frame. 'delta' is the elapsed time since the previous frame. // public override void _Process(float delta) // { // // } public override void _PhysicsProcess(float delta) { Vector2 inputVector = Vector2.Zero; animationState = (AnimationNodeStateMachinePlayback)animationTree.Get("parameters/playback"); inputVector.x = Input.GetActionStrength("ui_right") - Input.GetActionStrength("ui_left"); inputVector.y = Input.GetActionStrength("ui_down") - Input.GetActionStrength("ui_up"); inputVector = inputVector.Normalized(); if (inputVector != Vector2.Zero) { // Set animation tree blend position values based on inputVector value animationTree.Set("parameters/Idle/blend_position", inputVector); animationTree.Set("parameters/Run/blend_position", inputVector); animationState.Travel("Run"); velocity = velocity.MoveToward(inputVector * MAX_SPEED, ACCELERATION * delta); } else { animationState.Travel("Idle"); // Move velocity = velocity.MoveToward(Vector2.Zero, FRICTION * delta); } velocity = MoveAndSlide(velocity); }
public override void _Process(float delta) { var velocity = new Vector2(); if (Input.IsActionPressed("ui_right")) { speedAccumulator += 66; velocity.x += 1; } else if (Input.IsActionPressed("ui_left")) { speedAccumulator -= 66; velocity.x -= 1; } else { speedAccumulator *= 0.7f; } velocity = (velocity.Normalized() * Speed); velocity.x += speedAccumulator; prevVelocity = (int)velocity.x; Position += velocity * delta; Position = new Vector2( x: Mathf.Clamp(Position.x, 0 + _playerWidth * 2, _screenSize.x - _playerWidth * 2), y: Mathf.Clamp(Position.y, 0, _screenSize.y) ); }
//converts the `instruction` byte containing input instruction to a Vector2 `direction` public static Vector2 ProcessMovement(byte instruction) { Vector2 direction = Vector2.Zero; if ((instruction & (1 << 0)) != 0) { direction.x = 1; } else if ((instruction & (1 << 1)) != 0) { direction.x = -1; } if ((instruction & (1 << 2)) != 0) { direction.y = -1; } else if ((instruction & (1 << 3)) != 0) { direction.y = 1; } direction = direction.Normalized(); return(direction); }
public override void _PhysicsProcess(float delta) { velocity = GetInput(); velocity = velocity.Normalized() * speed; AnimatePlayer(); MoveAndSlide(velocity); }
private Vector2 CalculateMoveVector() { var moveVector = new Vector2(); if (Input.IsActionPressed("move_up")) { moveVector.y--; } if (Input.IsActionPressed("move_down")) { moveVector.y++; } if (Input.IsActionPressed("move_left")) { moveVector.x--; } if (Input.IsActionPressed("move_right")) { moveVector.x++; } moveVector = moveVector.Normalized(); return(moveVector); }
// Called every frame. 'delta' is the elapsed time since the previous frame. public override void _Process(float delta) { var velocity = new Vector2(); // The player's movement vector. if (Input.IsActionPressed("ui_right")) { velocity.x += 1; } if (Input.IsActionPressed("ui_left")) { velocity.x -= 1; } if (Input.IsActionPressed("ui_down")) { velocity.y += 1; } if (Input.IsActionPressed("ui_up")) { velocity.y -= 1; } var animatedSprite = GetNode <AnimatedSprite>("AnimatedSprite"); if (velocity.Length() > 0) { velocity = velocity.Normalized() * Speed; animatedSprite.Play(); } else { animatedSprite.Stop(); } Position += velocity * delta; Position = new Vector2( x: Mathf.Clamp(Position.x, 0, _screenSize.x), y: Mathf.Clamp(Position.y, 0, _screenSize.y) ); if (velocity.x != 0) { animatedSprite.Animation = "walk"; animatedSprite.FlipV = velocity.y > 0 || (velocity.y == 0 && _isLastFrameYInverted); // See the note below about boolean assignment animatedSprite.FlipH = velocity.x < 0; } else if (velocity.y != 0) { animatedSprite.Animation = "up"; animatedSprite.FlipV = velocity.y > 0; } if (velocity.y != 0) { _isLastFrameYInverted = velocity.y > 0; } }
public override void _Process(float delta) { Vector2 velocity = new Vector2(); Vector2 targetVec = TargetLocation - Position; if (CanMove) { // If Node will pass up target at max speed if (targetVec.Length() / delta <= speed) { // Move the distance from node to target velocity = targetVec; } else { // Move at constant speed velocity = targetVec.Normalized() * speed; } MoveAndSlide(velocity); if (Position == TargetLocation) { CanMove = false; } } }
public virtual void Update() { //Using the update method he follows the path if (Target != null) { Vector2 destination = new Vector2(Target.X, Target.Y); Vector2 dir = destination - sprite.position; float distance = dir.Length; if (distance < 0.03f) { currNode = Target; sprite.position = destination; if (path.Count > 0) { Target = path[0]; path.RemoveAt(0); } else { Target = null; } } else { sprite.position += (dir.Normalized() * speedBost) * Program.Window.deltaTime; } } }
public bool RayTraceCollision(Vector2 start, Vector2 end, Vector2 size, out Vector2 freepos, Entity e = null) { Vector2 diffVector = end - start, directionVector = diffVector.Normalized(); int accuracy = 1 + (int)(diffVector.Length * 6); float step = diffVector.Length / accuracy; Vector2 checkpos = start; for (int i = 0; i < accuracy; i++) { Vector2 buffer = checkpos; buffer += directionVector * step; if (GetCollision(buffer, size, e)) { freepos = checkpos; return(true); } checkpos = buffer; } freepos = end; return(false); }
// Called every frame. 'delta' is the elapsed time since the previous frame. public override void _PhysicsProcess(float delta) { Vector2 inputDirection = Vector2.Zero; Boolean inputMagnitude = false; mousePos = GetLocalMousePosition(); //Movement inputDirection.x = Input.GetActionStrength("ui_right") - Input.GetActionStrength("ui_left"); inputDirection.y = Input.GetActionStrength("ui_down") - Input.GetActionStrength("ui_up"); inputDirection = inputDirection.Normalized(); if (inputDirection != Vector2.Zero) { inputMagnitude = true; } else { inputMagnitude = false; } if (inputMagnitude) { velocity = velocity.MoveToward(inputDirection * maxSpeed, acceleration * delta); } else { velocity = velocity.MoveToward(Vector2.Zero, friction * delta); } velocity = MoveAndSlide(velocity); }
public List <T> RayTraceActor <T>(Vector2 start, Vector2 end, Vector2 size, params Actor[] exclude) where T : Actor { List <T> returnList = new List <T>(); List <Actor> excludeList = new List <Actor>(exclude); Vector2 diffVector = end - start, directionVector = diffVector.Normalized(); int accuracy = 1 + (int)(diffVector.Length * 6); float step = diffVector.Length / accuracy; Vector2 checkpos = start; for (int i = 0; i < accuracy; i++) { checkpos += directionVector * step; T a = GetActorAtPos <T>(checkpos, size, excludeList.ToArray()); if (a == null) { continue; } returnList.Add(a); excludeList.Add(a); } return(returnList); }
Vector2 seperate(List <IndividualParticle> neighbors) { Vector2 steer = new Vector2(); int count = 0; foreach (IndividualParticle particle in neighbors) { float distanceTo = Position.DistanceTo(particle.Position); if (distanceTo > 0 && distanceTo < minimumSeperation) { Vector2 difference = Position - particle.Position; difference = difference.Normalized(); difference = difference / distanceTo; steer += difference; count++; } } if (count > 0) { steer = steer / (float)count; } if (steer.Length() > 0) { steer = steer.Normalized(); steer *= maxSpeed; steer -= velocity; steer = steer.Clamped(maxForce); } return(steer); }
public override void AI() { Lighting.AddLight(projectile.Center, _data.color.ToVector3() * _data.lightStrength); CreateDust(); // Update target position until it dies // If target dies before projectile hits, target last live position UpdateTargetPosition(); // Despawn when projectile reaches destination Vector2 offset = _targetPosition - projectile.Center; float distanceSquared = offset.LengthSquared(); if (distanceSquared < SpeedSquared) { projectile.velocity = offset; if (projectile.timeLeft > 2) { projectile.timeLeft = 2; } return; } // Increase homing strength over time TickTimerOrValue(ref _currentLerpDelay, _data.homingIncreaseDelay, ref _lerp, 1, _data.homingIncreaseRate); // Increase speed over time TickTimerOrValue(ref _currentAccelerationDelay, _data.projectileSpeedIncreaseDelay, ref _speed, 30, _data.projectileSpeedIncreaseRate); projectile.velocity = Vector2.Lerp(projectile.velocity.Normalized(), offset.Normalized(), _lerp) * _speed; }
Vector2 cohese(List <IndividualParticle> neighbors) { Vector2 sum = new Vector2(0, 0); int count = 0; foreach (IndividualParticle particle in neighbors) { float distanceTo = Position.DistanceTo(particle.Position); if (distanceTo > 0 && distanceTo < neighborDistance) { sum += particle.Position; count++; } } if (count > 0) { sum /= count; Vector2 desiredDir = sum - Position; desiredDir = desiredDir.Normalized(); desiredDir *= maxSpeed; Vector2 steer = desiredDir - velocity; steer = steer.Clamped(maxForce); return(steer); } return(new Vector2(0, 0)); }
private void GetInput() { velocity = new Vector2(); if (Input.IsActionPressed("right")) { animatedSprite.FlipH = false; velocity.x += 1; } if (Input.IsActionPressed("left")) { animatedSprite.FlipH = true; velocity.x -= 1; } if (Input.IsActionPressed("down")) { velocity.y += 1; } if (Input.IsActionPressed("up")) { velocity.y -= 1; } if (Input.IsActionPressed("shoot")) { Shoot(); } velocity = velocity.Normalized(); }
protected override void UpdateLocal(ElapsedTime elapsedTime) { if (!Playing) { Direction = Vector2.Zero; CurrentSpeed = 0; return; } float deltaTime = elapsedTime.GetDelta(this); Time += deltaTime; Position = StartPosition + Trajectory.GetPositionAtTime(Time, out float newProgress); Progress = newProgress; Vector2 move = Position - LastPosition; Direction = move.Normalized(); Distance += move.Length(); CurrentSpeed = Distance / deltaTime; if (Progress >= 1f) { Position = Trajectory.Destination; Distance -= (Time - Trajectory.Duration) * Speed; Time = Trajectory.Duration; Progress = 1; End(); } LastPosition = Position; }
protected bool CheckVisiblePlayers() { bool returnVal = false; VisiblePlayers.Clear(); foreach (Player p in ((PlayScene)Game.CurrentScene).Players) { if (!p.IsActive) { continue; } Vector2 distance = p.Position - this.Position; if (distance.Length <= SightRadius)//he's quite near { Vector2 distDirection = distance.Normalized(); Vector2 rotationDirection = new Vector2((float)Math.Cos(Rotation), (float)Math.Sin(Rotation)); float deltaAngle = (float)Math.Acos(Vector2.Dot(distDirection, rotationDirection)); if (deltaAngle <= HalfConeAngle)//he's inside my field of view { VisiblePlayers.Add(p); returnVal = true; } } } return(returnVal); }
public override void _PhysicsProcess(float delta) { base._PhysicsProcess(delta); if (state == EPlayerState.STATE_DYING || state == EPlayerState.STATE_STUNNED || state == EPlayerState.STATE_DODGING) { return; } Vector2 motion = new Vector2( Input.GetActionStrength("move_right") - Input.GetActionStrength("move_left"), Input.GetActionStrength("move_down") - Input.GetActionStrength("move_up") ); SlowDown(motion, delta); if (motion.Length() > 0) { velocity = (velocity + motion.Normalized() * Acceleration * delta).Clamped(MaxVelocity); } KinematicCollision2D result = MoveAndCollide(velocity * delta); if (IsInstanceValid(result)) { velocity = new Vector2( Mathf.Abs(result.Normal.x) > 0? 0 : velocity.x, Mathf.Abs(result.Normal.y) > 0? 0 : velocity.y ); MoveAndCollide(result.Remainder); } }
public override void _IntegrateForces(Physics2DDirectBodyState state) { EmitSignal("_forces_integrated", new object[] { state }); if (jelly == null) { return; } float damping = jelly.damping; float stiffness = jelly.stiffness; Vector2 totalImpulse = Vector2.Zero; foreach (Neighbour n in neighbours) { JellyAtom neighbourAtom = n.jellyAtom; Vector2 posNeighbour = neighbourAtom.GlobalPosition; Vector2 selfPos = state.Transform.origin; float restLength = n.restLength; Vector2 diff = posNeighbour - selfPos; float distanceToNeighbour = diff.Length(); Vector2 diffNormalized = diff / distanceToNeighbour; Vector2 selfVelocity = state.LinearVelocity; Vector2 neighbourVelocity = neighbourAtom.LinearVelocity; float force = (distanceToNeighbour - restLength) * stiffness + (diffNormalized).Dot(neighbourVelocity - selfVelocity) * damping; totalImpulse += force * diff.Normalized() * state.Step; } ApplyCentralImpulse(totalImpulse); }
public void Physics_Update(float delta) { // Use Steering Behaviour to "move" the player to the hook, adding a pushing force when he arrive on it _velocity = Utils.Steering_Seek(_velocity, Utils.StateMachine_Player.RootNode.GlobalPosition, _target_GlobalPosition, HookMaxSpeed * _velocity_multiplier); _velocity = (_velocity.Length() > PushWhenArrive) ? _velocity : _velocity.Normalized() * PushWhenArrive; _velocity = Utils.StateMachine_Player.RootNode.MoveAndSlide(_velocity, Utils.VECTOR_FLOOR); // Get distance to the target float distance = Utils.GetDistanceBetween_2_Objects(Utils.StateMachine_Player.RootNode.GlobalPosition, _target_GlobalPosition); // Check if we are less that 1 frame (_velocity.Length() * delta) from the target to apply the push and change state if (distance < (_velocity.Length() * delta)) { _velocity = _velocity.Normalized() * PushWhenArrive; Godot.Collections.Dictionary <string, object> param = new Godot.Collections.Dictionary <string, object>(); param.Add("velocity", _velocity); Utils.StateMachine_Player.TransitionTo("Move/Air", param); } if (Utils.StateMachine_Player.RootNode.IsOnFloor()) { Utils.StateMachine_Player.TransitionTo("Move/Run", Utils.StateMachine_Player.TransitionToParam_Void); } }
public override void AI() { //Main.player[projectile.owner].chatOverhead.NewMessage(projectile.velocity.Length().ToString(), 5); int hooksOut = 0; for (int l = 0; l < 1000; l++) { if (Main.projectile[l].active && Main.projectile[l].owner == Main.myPlayer && Main.projectile[l].type == projectile.type) { hooksOut++; if (hooksOut >= 3) // This hook can have 1 hook out. { Main.projectile[l].tileCollide = false; } } } for (int i = 0; i < Main.item.Length; i++) { if ((Main.item[i].position - projectile.position).Length() <= 80) { Vector2 thatvector = (projectile.Center - Main.item[i].Center); Vector2 thisstaticvector = projectile.Center - Main.item[i].Center; thisstaticvector = thisstaticvector.Normalized() * Math.Min(thatvector.Length(), 12.5f); Main.item[i].velocity = (thatvector / 5.5f) + thisstaticvector; } } if (projectile.ai[0] == 2) { projectile.Kill(); } }
public void GetInput() { velocity = new Vector2(); if (Input.IsActionPressed("right")) { velocity.x += 1; } if (Input.IsActionPressed("left")) { velocity.x -= 1; } if (Input.IsActionPressed("down")) { velocity.y += 1; } if (Input.IsActionPressed("up")) { velocity.y -= 1; } velocity = velocity.Normalized() * Speed; }
public void GetInput() { Velocity = new Vector2(); if (Input.IsActionPressed("ui_left")) { Velocity.x += -1; } if (Input.IsActionPressed("ui_right")) { Velocity.x += 1; } if (Input.IsActionPressed("ui_up")) { Velocity.y += -1; } if (Input.IsActionPressed("ui_down")) { Velocity.y += 1; } if (Velocity.Length() > 0) { Velocity = Velocity.Normalized() * Speed; } }
static void Main(string[] args) { Vector2 v2 = new Vector2(4, 4); Vector2 res = v2.Normalized(); Console.WriteLine("Hello World! {0}", res); }
public void Normalize() { Vector2 v1 = new Vector2(2, -2); Vector2 v2 = new Vector2(2, -2); v1.Normalize(); var expectedResult = new Vector2(0.7071068f, -0.7071068f); Assert.That(expectedResult, Is.EqualTo(v1).Using(Vector2Comparer.Epsilon)); var normalizedV2 = Vector2.Normalize(v2); Assert.That(expectedResult, Is.EqualTo(normalizedV2).Using(Vector2Comparer.Epsilon)); Assert.That(expectedResult, Is.EqualTo(v2.Normalized()).Using(Vector2Comparer.Epsilon)); Assert.That(expectedResult, Is.Not.EqualTo(v2).Using(Vector2Comparer.Epsilon)); }
private void AggressiveWorker() { if (Timer.Get("shotTimer") <= 0) { var myPos = new Vector2(X, Y); foreach (var enemy in World.SpawnedObjects[2]) { var diff = new Vector2(enemy.X, enemy.Y) - myPos; if (diff.LengthFast < RangeRadius) { Shot(diff.Normalized()); break; } } } }