private void Work(object state) { this.state = ActorState.Running; ActorContinuation actorContinuation = ActorContinuation.Done; do { IMessage message = null; lock (this.mailBox) { message = this.mailBox.Peek(); } actorContinuation = this.OnReceiveMessage(message); lock (this.mailBox) { this.mailBox.Dequeue(); if (this.mailBox.Count == 0) { this.state = ActorState.Idle; break; } } } while (actorContinuation == ActorContinuation.BlockOnReceive); if (actorContinuation == ActorContinuation.Done) { this.actorManager.CompleteByActor(this); this.state = ActorState.Completed; } }
public void AddState(ActorState state, bool current = false) { States.Add (state.Name, state); if (current) CurrentStateKey = state.Name; }
public void JoeIsThirsty() { var thirsty = new ActorState(); thirsty.isSolvedBy(water); joe.thinks(joe).isNow(thirsty); // Maybe abstract this into an injectable state world.thinks(joe).isNow(thirsty); }
// ================================================================================ // private // -------------------------------------------------------------------------------- private void ActorStateChanged(IActor activeActor, ActorState state) { //if (state == ActorState.Dead && toBackgroundWhenDead == true) //{ // // set a bit further towards background // _transform.position = new Vector3(_transform.position.x, _transform.position.y, _transform.position.y + 1.0f + offset); // _isActive = false; //} // reset depth rendering when actor is active again if (activeActor.isAlive && !_isActive) _isActive = true; }
// ================================================================================ // private methods // -------------------------------------------------------------------------------- void Actor_StateChanged(IActor actor, ActorState state) { if (!actor.isAlive) { if (actors.Contains(actor)) { Remove(actor); } else { actor.stateChanged -= Actor_StateChanged; } } }
internal void EnqueueByActorManager(IMessage message) { if (this.state == ActorState.Completed) { throw new Exception("Actor already completed!"); } bool shouldScheduleWork = false; lock (this.mailBox) { if (this.mailBox.Count == 0) { shouldScheduleWork = true; } this.mailBox.Enqueue(message); } if (shouldScheduleWork) { this.state = ActorState.Scheduled; ThreadPool.QueueUserWorkItem(this.Work); } }
public StateSyncMessage(ActorState state) { State = state; }
public async Task <bool> IsInitializedAsync() { ActorState State = await StateManager.GetStateAsync <ActorState>(StateKey); return(State.IsInitialized); }
public void SetState(ActorState _state) { state = _state; anim.SetInteger("state", (int)state); }
public void Start() { floorLayer = LayerMask.NameToLayer("Floor"); actorState = ActorState.Alive; }
public void ResetState() { this.currentState = ActorState.Idle; this.bHasActed = false; this.bHasMoved = false; }
public Projectile(ActorState state) : base(state) { flags |= ActorFlags.NoBlockmap; }
public void Stop() { state = ActorState.Stop; }
public async Task ReceiveReminderAsync(string reminderName, byte[] context, TimeSpan dueTime, TimeSpan period) { if (reminderName.Equals(CheckProvision)) { var disPatcherId = this.Id.GetStringId();//Subscription/ResourceGroup/clustername/nodename; var dispatcher = await ClusterConfigStore.GetMessageClusterResourceAsync(disPatcherId) as ClusterDispatcherInfo; ActorState State = await StateManager.GetStateAsync <ActorState>(StateKey); if (State.Keys == null || !State.Keys.IsAccessible) { var authRuleResourceId = dispatcher.Properties.ServiceBus.AuthRuleResourceId; var client = new ArmClient(await this.GetConfigurationInfo().GetAccessToken()); State.Keys = await client.ListKeysAsync <ServicebusAuthorizationKeys>(authRuleResourceId, "2015-08-01"); } if (!State.Keys.IsAccessible) { Logger.Warn("Servicebus keys are not accessible"); return; } Logger.Debug($"Setting up {dispatcher.Name}"); var ns = NamespaceManager.CreateFromConnectionString(State.Keys.PrimaryConnectionString); var filters = dispatcher.Properties.CorrelationFilters; for (int i = 0, ii = dispatcher.Properties.TopicScaleCount; i < ii; ++i) { var topicPath = dispatcher.Name + i.ToString("D3"); if (!await ns.TopicExistsAsync(topicPath)) { await ns.CreateTopicAsync(topicPath); } foreach (var correlationFilter in filters.Keys) { var queueId = disPatcherId.Split('/'); queueId[queueId.Length - 1] = filters[correlationFilter]; var queueActor = ActorProxy.Create <IQueueManagerActor>(new ActorId(string.Join("/", queueId))); var forwardPath = await queueActor.GetPathAsync(); var name = dispatcher.Name + "2" + forwardPath; if (!await ns.SubscriptionExistsAsync(topicPath, name)) { Logger.DebugFormat($"Creating Subscription for {name}"); await ns.CreateSubscriptionAsync( new SubscriptionDescription(topicPath, name) { ForwardTo = forwardPath, }, new CorrelationFilter(correlationFilter)); } else { Logger.DebugFormat($"Subscription '{name}' already created"); } } } State.IsInitialized = true; await StateManager.SetStateAsync(StateKey, State); await UnregisterReminderAsync(GetReminder(reminderName)); } }
public override void Enter(Actor actor, ActorState oldState) { base.Enter(actor, oldState); m_playerInput = ReInput.players.GetPlayer(0); }
public Actor(ActorManager actorManager) { this.actorManager = actorManager; this.mailBox = new Queue<IMessage>(); this.state = ActorState.Idle; }
public void RemoveState(ActorState state) { States.Remove (state.Name); }
public StateEventArgs(ActorState state) { m_state = state; }
private void Update() { if (play) { // Itterate through replay data frames until there's no more frames or the data frame's time // is past our time value. while (rlFrameNum < replay.Frames.Count && time >= replay.Frames[rlFrameNum].Time) { Frame rlFrame = replay.Frames[rlFrameNum]; // Itterate through Rocket League objects (ActorStates). for (int i = 0; i < rlFrame.ActorStates.Count; i++) { ActorState actorState = rlFrame.ActorStates[i]; GameObject rlObj = null; // If RL object has just been created, spawn a new GameObject for it. if (actorState.State == ActorStateState.New) { // Make sure there is not an existing object with the same ID. // Not sure what would would cause this. if (rlObjects.ContainsKey(actorState.Id)) { Debug.Log("Duplicate object ID " + actorState.Id); } else { rlObj = GetNewRlObject(actorState); rlObjects.Add(actorState.Id, rlObj); } } // Otherwise we should be able to get the object from the dictionary. else { // Make sure the dictionary actually has the object. // I think ActorStates only have a valid class type on the frame they are created, // so I don't think we can just spawn a missing object here. if (!rlObjects.ContainsKey(actorState.Id)) { Debug.Log("Missing object ID " + actorState.Id); } else { rlObj = rlObjects[actorState.Id]; } } // If everthing went correctly getting the object... if (rlObj != null) { // If the object is being deleted, destroy it. if (actorState.State == ActorStateState.Deleted) { rlObjects.Remove(actorState.Id); Destroy(rlObj); } // Otherwise update the object's state. else { UpdateObjectState(actorState); } } } rlFrameNum++; } time += Time.deltaTime; } }
private void Actor_StateChanged(IActor actor, ActorState state) { if (!actor.isAlive) { DisableTarget(); if (targetEvent != null) { targetEvent(TargetEventType.CannotReachTarget); } } }
public void SetState(ActorState state) { _actorState = state; }
void PolyBody_Collided(RigidBody sender, object delta) { var colD = (CollisionEventData)delta; var axis = colD.Axis; if ((axis + Vector2.UnitY).LengthSquared() < 0.01f) { canChangeState = true; if (changeToState.Name != "Empty") { State = changeToState; FacingDirection = changeToDirection; changeToState = new ActorState("Empty"); } } }
public void Destroy() { m_state = ActorState.Destroyed; if(m_onDestroy != null) m_onDestroy(); }
internal void Start() { this.state = ActorState.Running; }
public void SetPlayerState(ActorState newState, GameControler.PlayerEventArgs e) { if (canChangeState) { FacingDirection = e.Direction.GetVector(FacingDirection); State = newState; } else if (newState.Name == JumpingState.Name || newState.Name == WalkingState.Name) { if (e.Direction.GetName() != GameControler.Directions.Static.GetName()) { FacingDirection = e.Direction.GetVector(FacingDirection); var s = Math.Sign(PolyBody.Velocity.X); var t = s * MaxFlySpeed - PolyBody.Velocity.X; if (Math.Abs(t) <= MaxFlySpeed) // { PolyBody.Velocity += FacingDirection * new Vector2(MaxFlySpeed / 10, 0); // move.f = WalkForce * FacingDirection * Vector2.UnitX; } else if (Math.Abs(PolyBody.Velocity.X) >= MaxFlySpeed) { PolyBody.Velocity = new Vector2(FacingDirection.X * MaxFlySpeed, PolyBody.Velocity.Y); } } } else { changeToDirection = e.Direction.GetVector(FacingDirection); changeToState = newState; } }
internal void Stop() { this.state = ActorState.Stopped; }
// Update is called once per frame public virtual void Update() { //ActorState checks switch (this.CurrentActorState) { case ActorState.Dead: //Gracefully destroy the actor this.DestroyActor(); break; case ActorState.Alive: //HP check for death if (this.CurrentHitPoints <= 0) this.CurrentActorState = ActorState.Dead; break; } }
private bool CastRay(int XOffset) { RaycastHit2D Ray; RaycastHit2D StepRay; int PlayerLayer = LayerMask.NameToLayer("Player"); int TileLayer = LayerMask.NameToLayer("Tile"); int Mask = 1 << PlayerLayer; int StepMask = 1 << TileLayer; /*Debug.Log("Casting Yellow RAY (" + TileLayer +"," + XOffset + ")!"); * Vector3 LegPosition = new Vector3(ArmPosition.position.x,ArmPosition.position.y - 3f,ArmPosition.position.z); * Ray = Physics2D.Raycast(LegPosition,Vector2.left * XOffset,SightDistance,1<<TileLayer); * Debug.DrawRay(LegPosition,Vector3.left*SightDistance,Color.yellow,1); * if( Ray.collider != null ) { * Debug.Log("Yellow Collider: " + Ray.collider.name); * if( Ray.collider.name == "Tilemap" ) { * float TileDistance = Vector3.Distance(Ray.collider.transform.position,transform.position); * //Debug.Log("Tile Distance: " + TileDistance); * if( Ray.collider.transform.position.y < transform.position.y && TileDistance < 24 ) { * CurrentState = ActorState.AS_JUMP; * return true; * } * } * }*/ float StepDistance = 3f; Vector3 StepCheck = new Vector3((ArmPosition.position.x + GroundCheck.position.x) / 2, GroundCheck.position.y + 2f, 0f); StepRay = Physics2D.Raycast(StepCheck, Vector2.left * XOffset, StepDistance, StepMask); Debug.DrawRay(StepCheck, Vector3.left * StepDistance, Color.blue, 1); if (StepRay.collider != null) { if (StepRay.collider.name == "Tilemap") { //If we are near enough the edge...jump! float ObstacleDistance = Vector3.Distance(StepRay.collider.transform.position, StepCheck); Debug.Log("Obstacle at " + ObstacleDistance); CurrentState = ActorState.AS_JUMP; return(true); } } else { Ray = Physics2D.Raycast(ArmPosition.position, Vector2.left * XOffset, SightDistance, Mask); Debug.DrawRay(ArmPosition.position, Vector3.left * SightDistance, Color.red, 1); if (Ray.collider != null) { if (Ray.collider.tag == "Player") { TargetPosition = Ray.collider.transform.position; if (Vector3.Distance(TargetPosition, transform.position) < 20) { Flip(GetCurrentPlayerDirection()); CurrentState = ActorState.AS_ATTACK; } else { CurrentState = ActorState.AS_CHASE; } return(true); } } } return(false); }
public override void Exit(ActorState NextGameState) { mActor = null; }
protected override void ExecuteState0(ActorState state, float deltaTime) { state.ExecuteTower(this, deltaTime); }
public PlayerPawn(ActorState state) : base(state) { Player = null; }
public override void EnterState(ActorState state) { state.EnterTower(this); }
public async Task <string> GetPathAsync() { ActorState State = await StateManager.GetStateAsync <ActorState>(StateKey); return(State.Path); }
public void SendRemoveActor(ExecutionGroup source, ActorState actorState) { m_IncomingMessages[source.m_Index].TryEnqueue(CreateRemoveActorMessage(source, actorState)); m_HasPendingIncomingMessages = true; Signal(); }
public async Task ReceiveReminderAsync(string reminderName, byte[] context, TimeSpan dueTime, TimeSpan period) { if (reminderName.Equals(CheckProvision)) { ActorState State = await StateManager.GetStateAsync <ActorState>(StateKey); try { var nodeKey = this.Id.GetStringId();//Subscription/ResourceGroup/clustername/nodename; var queue = await ClusterConfigStore.GetMessageClusterResourceAsync(nodeKey) as ClusterQueueInfo; if (!State.IsInitialized) { var client = new ArmClient(await this.GetConfigurationInfo().GetAccessToken()); if (State.Keys == null || !State.Keys.IsAccessible) { var authRuleResourceId = queue.Properties.ServiceBus.AuthRuleResourceId; State.Keys = await client.ListKeysAsync <ServicebusAuthorizationKeys>(authRuleResourceId, "2015-08-01"); State.Path = queue.Name; } if (!State.Keys.IsAccessible) { Logger.Error("Servicebus keys are not accessible"); return; } // queue.Properties.ServiceBus.ServicebusNamespaceId var ns = NamespaceManager.CreateFromConnectionString(State.Keys.PrimaryConnectionString); if (!await ns.QueueExistsAsync(queue.Name)) { var qd = queue.Properties.QueueDescription; if (qd == null) { Logger.Warn("Servicebus queue do not exist"); return; } var q = new QueueDescription(queue.Name); if (qd.AutoDeleteOnIdle.IsPresent()) { q.AutoDeleteOnIdle = XmlConvert.ToTimeSpan(qd.AutoDeleteOnIdle); } if (qd.DefaultMessageTimeToLive.IsPresent()) { q.DefaultMessageTimeToLive = XmlConvert.ToTimeSpan(qd.DefaultMessageTimeToLive); } if (qd.DuplicateDetectionHistoryTimeWindow.IsPresent()) { q.RequiresDuplicateDetection = true; q.DuplicateDetectionHistoryTimeWindow = XmlConvert.ToTimeSpan(qd.DuplicateDetectionHistoryTimeWindow); } q.EnableBatchedOperations = qd.EnableBatchedOperations; q.EnableDeadLetteringOnMessageExpiration = qd.EnableDeadLetteringOnMessageExpiration; q.EnableExpress = qd.EnableExpress; q.EnablePartitioning = qd.EnablePartitioning; if (qd.ForwardDeadLetteredMessagesTo.IsPresent()) { q.ForwardDeadLetteredMessagesTo = qd.ForwardDeadLetteredMessagesTo; } if (qd.ForwardTo.IsPresent()) { q.ForwardTo = qd.ForwardTo; } await ns.CreateQueueAsync(q); } State.IsInitialized = true; } if (State.IsInitialized) { var ns = NamespaceManager.CreateFromConnectionString(State.Keys.PrimaryConnectionString); var config = this.GetConfigurationInfo(); var sbQueue = await ns.GetQueueAsync(queue.Name); Logger.Info($"Checking Queue information for {sbQueue.Path}, {sbQueue.MessageCount}, {sbQueue.MessageCountDetails.ActiveMessageCount}, {sbQueue.MessageCountDetails.DeadLetterMessageCount}, {sbQueue.MessageCountDetails.ScheduledMessageCount}, {sbQueue.MessageCountDetails.TransferDeadLetterMessageCount}, {sbQueue.MessageCountDetails.TransferMessageCount}"); var parts = nodeKey.Split('/'); var applicationName = new Uri($"fabric:/{parts[parts.Length - 2]}"); var serviceName = new Uri($"fabric:/{parts[parts.Length - 2]}/{parts[parts.Length-1]}"); var vmssManager = ActorProxy.Create <IVmssManagerActor>(new ActorId(string.Join("/", parts.Take(parts.Length - 1)) + "/" + queue.Properties.ListenerDescription.ProcessorNode)); var fabricClient = GetFabricClient(); var primNodes = 0; if (queue.Properties.ListenerDescription.UsePrimaryNode) { var nodes = await fabricClient.QueryManager.GetNodeListAsync(); primNodes = nodes.Aggregate(0, (c, p) => c + (p.NodeType == config.PrimaryScaleSetName ? 1 : 0)); } await vmssManager.ReportQueueMessageCountAsync(Id.GetStringId(), sbQueue.MessageCountDetails.ActiveMessageCount, primNodes); if (sbQueue.MessageCountDetails.ActiveMessageCount > 0 || queue.Properties.ListenerDescription.AlwaysOn) { //Handle Listener Application Deployment var listenerDescription = queue.Properties.ListenerDescription; var apps = await fabricClient.QueryManager.GetApplicationListAsync(applicationName); if (!apps.Any()) { var appTypes = await fabricClient.QueryManager.GetApplicationTypeListAsync(listenerDescription.ApplicationTypeName); if (!appTypes.Any(a => a.ApplicationTypeVersion == listenerDescription.ApplicationTypeVersion)) { Logger.Error("The listener application was not registed with service fabric"); return; } await fabricClient.ApplicationManager.CreateApplicationAsync(new ApplicationDescription { ApplicationName = applicationName, ApplicationTypeName = listenerDescription.ApplicationTypeName, ApplicationTypeVersion = listenerDescription.ApplicationTypeVersion, }); } var registered = await fabricClient.QueryManager.GetServiceListAsync(applicationName, serviceName); if (!registered.Any()) { var serviceType = await fabricClient.QueryManager.GetServiceTypeListAsync(listenerDescription.ApplicationTypeName, listenerDescription.ApplicationTypeVersion, listenerDescription.ServiceTypeName); if (!serviceType.Any()) { Logger.Error("The listener application service type was not registed with service fabric"); return; } try { var listenerConfiguration = new MessageProcessorOptions { ConnectionString = State.Keys.PrimaryConnectionString, QueuePath = sbQueue.Path, }; var placementConstraints = $"NodeTypeName == {queue.Properties.ListenerDescription.ProcessorNode}"; if (queue.Properties.ListenerDescription.UsePrimaryNode) { placementConstraints += " || isPrimary == true"; } await fabricClient.ServiceManager.CreateServiceAsync(new StatelessServiceDescription { ServiceTypeName = listenerDescription.ServiceTypeName, //QueueListenerService.ServiceType, // ServiceFabricConstants.ActorServiceTypes.QueueListenerActorService, ServiceName = serviceName, PartitionSchemeDescription = new UniformInt64RangePartitionSchemeDescription { PartitionCount = queue.Properties.ListenerDescription.PartitionCount, LowKey = Int64.MinValue, HighKey = Int64.MaxValue }, InstanceCount = -1, //One for each node, PlacementConstraints = placementConstraints, // $"NodeTypeName == {queue.Properties.ListenerDescription.ProcessorNode}", ApplicationName = applicationName, InitializationData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(listenerConfiguration)), }); } catch (Exception ex) { Logger.ErrorException("Could not register service for queue", ex); throw; } } } else { if ((DateTimeOffset.UtcNow - (XmlConvert.ToTimeSpan(queue.Properties.ListenerDescription.IdleTimeout))) > sbQueue.AccessedAt) { // await vmssManager.SetCapacityAsync(0); var registered = await fabricClient.QueryManager.GetServiceListAsync(applicationName, serviceName); if (registered.Any()) { await fabricClient.ServiceManager.DeleteServiceAsync(new DeleteServiceDescription(serviceName) { }); } } } } } catch (Exception ex) { Logger.ErrorException("Reminder Error:", ex); throw; } finally { await StateManager.SetStateAsync(StateKey, State); } } }
void SendRemoveActorResponse(ExecutionGroup source, ActorState actorState) { m_IncomingMessages[source.m_Index].TryEnqueue(CreateRemoveActorResponseMessage(source, actorState)); m_HasPendingIncomingMessages = true; // No need to Signal(), it's processed when the client Add() a new actor to the scheduler }
private void ValidatePlayer(SpaceMarine PlayerCharacter) { Weapon currentWeapon; Flag flag; Vector2 remotePosition = _packetReader.ReadVector2(); int remoteHealth = _packetReader.ReadInt32(); ActorState remoteState = GetState(_packetReader.ReadInt32()); int remoteScore = _packetReader.ReadInt32(); int remoteTeam = _packetReader.ReadInt32(); int weaponID = _packetReader.ReadInt32(); int weaponSpawnID = _packetReader.ReadInt32(); int flagID = _packetReader.ReadInt32(); int flagTeam = _packetReader.ReadInt32(); if (PositionInvalid(PlayerCharacter.Position, remotePosition)) { PlayerCharacter.Position = remotePosition; } if (remoteState != PlayerCharacter.State) { PlayerCharacter.State = remoteState; } if (weaponID != -1) { currentWeapon = (Weapon)getItem(weaponID); if (currentWeapon == null) { return; } currentWeapon.User = PlayerCharacter; if (weaponSpawnID != -1) { currentWeapon.SpawnID = weaponSpawnID; } if (PlayerCharacter.CurrentWeapon == null) { PlayerCharacter.CurrentWeapon = currentWeapon; } else if (currentWeapon.Name != PlayerCharacter.CurrentWeapon.Name) { PlayerCharacter.CurrentWeapon = currentWeapon; } } if (flagID != -1) { flag = (Flag)getItem(flagID); flag.Team = flagTeam; PlayerCharacter.FlagSlot = flag; } PlayerCharacter.Health = remoteHealth; PlayerCharacter.Score = remoteScore; PlayerCharacter.Team = remoteTeam; if (PlayerCharacter.Team == 1) { if (!_gameManager.MatchController.BlueTeam.Members.Contains(PlayerCharacter)) { _gameManager.MatchController.BlueTeam.AddTeamMember(PlayerCharacter); } } if (PlayerCharacter.Team == 2) { if (!_gameManager.MatchController.RedTeam.Members.Contains(PlayerCharacter)) { _gameManager.MatchController.RedTeam.AddTeamMember(PlayerCharacter); } } if (PlayerCharacter.Team == 0) { if (!_gameManager.MatchController.NoTeam.Members.Contains(PlayerCharacter)) { _gameManager.MatchController.NoTeam.AddTeamMember(PlayerCharacter); } } }
void SendStealActorResponse(ExecutionGroup source, ActorState actorState) { m_IncomingMessages[source.m_Index].TryEnqueue(CreateStealActorResponseMessage(source, actorState)); m_HasPendingIncomingMessages = true; Signal(); }
public void ChangeState(ActorState state) { switch( state ) { case ActorState.Initialize: { OnInitialize(); } break; case ActorState.Load: { OnLoadContent(); } break; } State = state; }
static ThreadMessage CreateAddActorMessage(ExecutionGroup source, ActorState actorState) { return(new ThreadMessage(MessageType.AddActor, source, actorState)); }
public void Move(Vector2 p) { double x1 = p.X; double y1 = p.Y; double x0 = position.X; double y0 = position.Y; double k = (y1 - y0) / (x1 - x0); double b = y0; double S = Math.Sqrt(Math.Pow((y0 - y1), 2) + Math.Pow((x0 - x1), 2)); double speed = this.speed; double t = S / speed; dxSpeed = (x1 - x0) / t; dySpeed = (y1 - y0) / t; endPoint.X = (float)x1; endPoint.Y = (float)y1; moveToLeft = (position.X >= endPoint.X) ? true : false; moveUp = (position.Y >= endPoint.Y) ? true : false; state = ActorState.Move; }
static ThreadMessage CreateRemoveActorResponseMessage(ExecutionGroup source, ActorState actorState) { return(new ThreadMessage(MessageType.RemoveActorResponse, source, actorState)); }
private void UpdatePosition(double ms) { if (state == ActorState.Stop) return; double deltaX = ms * dxSpeed; double deltaY = ms * dySpeed; position.X += (float)deltaX; position.Y += (float)deltaY; bool endMoveX = false, endMoveY = false; if ((moveToLeft && position.X <= endPoint.X) || (!moveToLeft && position.X >= endPoint.X)) { endMoveX = true; position.X = endPoint.X; dxSpeed = 0; } if ((moveUp && position.Y <= endPoint.Y) || (!moveUp && position.Y >= endPoint.Y)) { endMoveY = true; position.Y = endPoint.Y; dySpeed = 0; } if (endMoveY && endMoveX) { if (onMoveEnd != null) onMoveEnd(this); position.X = endPoint.X; position.Y = endPoint.Y; endPoint.X = float.NaN; endPoint.Y = float.NaN; state = ActorState.Stop; Raise("onmoveend", this); } if (onMove != null) onMove(this); Raise("onmove",this); }
public ThreadMessage(MessageType type, ExecutionGroup source, ActorState actorState) { Type = type; Source = source; ActorState = actorState; }
protected override Task OnActivateAsync() { if (this.State == null) { this.State = new ActorState() { Board = new int[9], Winner = "", Players = new List<Tuple<long, string>>(), NextPlayerIndex = 0, NumberOfMoves = 0 }; } return Task.FromResult(true); }
public override void AReady() //TODO Try moving everything non-visual to Physics Processing { PlayerSprite = GetNodeOrNull(new NodePath("PlayerSprite")) as AnimatedSprite3D; ActorDetectorArea = GetNodeOrNull(new NodePath("ActorDetector")) as Area; if (PlayerSprite == null || ActorDetectorArea == null) { GD.PrintErr("One or multiple required child nodes could not be found!"); } //Define states StandState = new ActorState(() => { //Enter State PlayerSprite.SetAnimation("Idle"); SnapToGround = true; }, (float delta) => { //Process State }, (float delta) => { //State Physics Processing //Switch to the walking state when directional input is given bool sideInput = Mathf.Abs(Input.GetActionStrength("p1_right") - Input.GetActionStrength("p1_left")) > 0; if (sideInput) { ChangeState(WalkState); } CanFall(); CanJump(); }, () => { //Exit State }); WalkState = new ActorState(() => { //Enter State PlayerSprite.SetAnimation("Walk"); SnapToGround = true; }, (float delta) => { //Process State }, (float delta) => { //State Physics Processing //Switch to the standing state when no directional input is given float sideInput = Input.GetActionStrength("p1_right") - Input.GetActionStrength("p1_left"); if (sideInput == 0) { ChangeState(StandState); } //Check if the player should be running, if yes go to run state bool isRunPressed = Input.GetActionStrength("p1_run") > 0; if (isRunPressed) { ChangeState(RunState); } //Move the player Vector2 movement = new Vector2(); movement.x = sideInput * WalkAcceleration; //movement.x = Mathf.Abs(Velocity.x) + Mathf.Abs(movement.x) > MaxWalkSpeed ? (MaxWalkSpeed - Mathf.Abs(Velocity.x)) * Mathf.Sign(movement.x) : movement.x; ApplyForce2D(movement); //Update the walking animation speed PlayerSprite.Frames.SetAnimationSpeed("Walk", (Mathf.Abs(Velocity.x) / 2) + 8); CanFall(); CanJump(); //Enforce walk speed limit if (Math.Abs(Velocity.x) >= MaxWalkSpeed) { Velocity.x = ClampedInterpolation.Lerp(Velocity.x, MaxWalkSpeed * Mathf.Sign(Velocity.x), GetElapsedTimeInState()); } }, () => { //Exit State }); RunState = new ActorState(() => { //Enter State PlayerSprite.SetAnimation("Walk"); SnapToGround = true; }, (float delta) => { //Process State }, (float delta) => { //State Physics Processing //Switch to the standing state when no directional input is given float sideInput = Input.GetActionStrength("p1_right") - Input.GetActionStrength("p1_left"); if (sideInput == 0) { ChangeState(StandState); } //Check if the player should be running, if not go back to walk state bool isRunPressed = Input.GetActionStrength("p1_run") > 0; if (!isRunPressed) { ChangeState(WalkState); } //Move the player Vector2 movement = new Vector2(); movement.x = sideInput * RunAcceleration; //movement.x = Mathf.Abs(Velocity.x) + Mathf.Abs(movement.x) > MaxRunSpeed ? (MaxRunSpeed - Mathf.Abs(Velocity.x)) * Mathf.Sign(movement.x) : movement.x; ApplyForce2D(movement); //Update the walking animation speed PlayerSprite.Frames.SetAnimationSpeed("Walk", Mathf.Max((Mathf.Abs(Velocity.x)) + 2, (Mathf.Abs(Velocity.x) / 2) + 8)); CanFall(); CanJump(); //Enforce walk speed limit if (Math.Abs(Velocity.x) >= MaxRunSpeed) { Velocity.x = ClampedInterpolation.Lerp(Velocity.x, MaxRunSpeed * Mathf.Sign(Velocity.x), GetElapsedTimeInState()); } }, () => { //Exit State }); JumpState = new ActorState(() => { //Enter State GD.Print("Jump"); PlayerSprite.SetAnimation("Jump"); SnapToGround = false; JumpSpeedBuffer = Velocity.x; //Add the initial force of the jump ApplyForce2D(new Vector2(0, JumpSpeed)); }, (float delta) => { //Process State }, (float delta) => { //State Physics Processing float jumpTime = GetElapsedTimeInState(); DebugText.Display("jumpTime", "Jump Time: " + jumpTime); //Add some force for extra air time if the jump button is held ApplyForce2D(Vector2.Up, Gravity.y * (1 - JumpSustainGravityMultiplier)); //Allow slight player movement float sideInput = Input.GetActionStrength("p1_right") - Input.GetActionStrength("p1_left"); Vector2 movement = new Vector2(); movement.x = sideInput * (AirAcceleration); ApplyForce2D(movement); //Exit state if required bool jumpPressed = Input.GetActionStrength("p1_jump") > 0; if (!jumpPressed || jumpTime > MaxJumpTime) { ChangeState(FallState); } if (IsOnFloor()) { ChangeState(StandState); } //Enforce air speed limit float speedLimit = Mathf.Min(Mathf.Abs(JumpSpeedBuffer), MaxRunSpeed); if (Mathf.Abs(Velocity.x) >= speedLimit) { Velocity.x = ClampedInterpolation.Lerp(Velocity.x, speedLimit * Mathf.Sign(Velocity.x), GetElapsedTimeInState()); } }, () => { //Exit State DebugText.Remove("jumpTime"); }); FallState = new ActorState(() => { //Enter State GD.Print("Fall"); SnapToGround = false; PlayerSprite.SetAnimation("Jump"); JumpSpeedBuffer = Velocity.x; }, (float delta) => { //Process State }, (float delta) => { //State Physics Processing //Allow slight player movement float sideInput = Input.GetActionStrength("p1_right") - Input.GetActionStrength("p1_left"); Vector2 movement = new Vector2(); movement.x = sideInput * (AirAcceleration); ApplyForce2D(movement); if (IsOnFloor() == true) { ChangeState(StandState); } //Enforce air speed limit /* if(PreviousState == RunState) { * if (Math.Abs(Velocity.x) > MaxRunSpeed) { Velocity.x = Interpolation.Lerp(Velocity.x, MaxRunSpeed * Mathf.Sign(Velocity.x), GetElapsedTimeInState()); } * } else { * if (Math.Abs(Velocity.x) > MaxWalkSpeed) { Velocity.x = Interpolation.Lerp(Velocity.x, MaxWalkSpeed * Mathf.Sign(Velocity.x), GetElapsedTimeInState()); } * } */ float speedLimit = Mathf.Min(Mathf.Abs(JumpSpeedBuffer), MaxRunSpeed); if (Mathf.Abs(Velocity.x) >= speedLimit) { Velocity.x = ClampedInterpolation.Lerp(Velocity.x, speedLimit * Mathf.Sign(Velocity.x), GetElapsedTimeInState()); } }, () => { //Exit State }); }
public void Begin() { m_state = ActorState.Active; if(m_onBegin != null) m_onBegin(); }
public BaseActorState(Actor ac) { m_actor = ac; m_stateName = "BaseActorState"; m_state = ActorState.OTHER; }
public void Standby() { m_state = ActorState.StandBy; if (m_onStandby != null) m_onStandby(); }
private void ActorStateChangedHandler(IActor activeActor, ActorState state) { if (state == ActorState.Dead) { SetAnimation(AvatarAnimation.die); } else if (state == ActorState.TakingAction) { SetAnimation(AvatarAnimation.attack); } else if (state == ActorState.Moving) { SetAnimation(AvatarAnimation.walk); } else if (state == ActorState.Idle) { SetAnimation(AvatarAnimation.idle); } }