public Color GetNodeColor(Node2D node) { if (node == start) { return Color.white * .5f + Color.red; } if (node == end) { return Color.white * .2f + Color.yellow; } if (node.Weight == WallWeight) { return Color.black; } if (node.Weight == GrassWeight) { return Color.white * .5f + Color.green; } if (node.Weight == WaterWeight) { return Color.white * .5f + Color.blue; } return Color.white; }
/// <summary> /// 初期化。スクリプトから動的に生成する場合に /// </summary> /// <param name="engine">ADVエンジン</param> public void InitOnCreate(AdvEngine engine, TextArea2D text, TextArea2D nameText, GameObject rootChildren, Node2D transrateMessageWindowRoot) { this.engine = engine; this.text = text; this.nameText = nameText; this.rootChildren = rootChildren; this.transrateMessageWindowRoot = transrateMessageWindowRoot; }
/// <summary> /// Gets distance from node A to node B /// </summary> /// <param name="a">node A</param> /// <param name="b">node B</param> /// <returns>Distance between node A and node B</returns> protected override double Distance(Node2D a, Node2D b) { var xd = a.X - b.X; var yd = a.Y - b.Y; var r = Math.Sqrt((xd * xd + yd * yd) / 10.0); var t = MathExtensions.NearestInt(r); return t < r ? t + 1 : t; }
/// <summary> /// コピーコンストラクタ /// </summary> /// <param name="source">コピーされるobject</param> public DelaunayElement2d(DelaunayElement2d source) { p = new List<Node2D>() { source.p[0], source.p[1], source.p[2] }; edge = new List<Edge2D>() { source.edge[0], source.edge[1], source.edge[2] }; // l = new double[3] { source.l[0], source.l[1], source.l[2] }; length_sq = new double[3] { source.length_sq[0], source.length_sq[1], source.length_sq[2] }; area = source.area; center = new Node2D(source.center); radius = source.radius; DeleteFlag = source.DeleteFlag; }
/// <summary> /// Gets distance from node A to node B /// </summary> /// <param name="a">node A</param> /// <param name="b">node B</param> /// <returns>Distance between node A and node B</returns> protected override double Distance(Node2D a, Node2D b) { var aGeo = new GeoLocation(a); var bGeo = new GeoLocation(b); var q1 = Math.Cos(aGeo.Longitude - bGeo.Longitude); var q2 = Math.Cos(aGeo.Latitude - bGeo.Latitude); var q3 = Math.Cos(aGeo.Latitude + bGeo.Latitude); var q1q2 = (1.0 + q1) * q2; var q1q3 = (1.0 - q1) * q3; var d2 = (q1q2 - q1q3) / 2; return (int)(EarthSphereRadius * Math.Acos(d2)) + 1; }
private double radius; // 外接円半径 #endregion Fields #region Constructors /// <summary> /// Element2dクラスの新規インスタンスを初期化し,各頂点情報(座標,ID)をセットする. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> public DelaunayElement2d(Node2D a, Node2D b, Node2D c) { p = new List<Node2D>() { a, b, c }; edge = new List<Edge2D>() { new Edge2D(a.ID, b.ID), new Edge2D(b.ID, c.ID), new Edge2D(c.ID, a.ID) }; // l = new double[3] { 0, 0, 0 }; length_sq = new double[3] { 0, 0, 0 }; center = new Node2D(0.0, 0.0); radius = 0; SetSideLength(); SetArea(); SetCircumscribedCircle(); DeleteFlag = false; }
public void FireWeapon(Node2D target, Weapon weapon) { if (weapon == Weapon.Missile) { // fire missile } else if (weapon == Weapon.Laser) { if (target is SpaceDamagable damagable) { damagable.Hit(); CanLaserFire = false; } } else if (weapon == Weapon.Railgun) { // fire rail } }
public override void _Ready() { _AnimationPlayer = GetNode <AnimationPlayer>("AnimationPlayer"); _Sprite = GetNode <Sprite>("Sprite"); _AnimationTree = GetNode <AnimationTree>("AnimationTree"); _YeetedCatDelayTimer = GetNode <Timer>("YeetedCatDelayTimer"); _AnimStateMachine = (AnimationNodeStateMachinePlayback) _AnimationTree.Get("parameters/playback"); _RightWallRaycasts = GetNode <Node2D>("RightWallRaycasts"); _LeftWallRaycasts = GetNode <Node2D>("LeftWallRaycasts"); _YeetedCatPrefab = (PackedScene)GD.Load("res://Scenes/YeetedCat.tscn"); _Hud = GetNode <HUD>("HUD"); _AudioStreamPlayer = GetNode <AudioStreamPlayer>("AudioStreamPlayer"); }
public void SpawnForge() { Forge node = forgeScene.Instance() as Forge; if (stats.Mana < node.ManaCost) { return; } stats.ManaDrain(node.ManaCost); Node2D gameNode = GetParent().GetParent() as Node2D; Node2D heroNode = GetParent() as KinematicBody2D; node.Position = new Vector2((heroNode.Position.x + direction * wallSpawnPoint.x), heroNode.Position.y); node.Direction = direction; node.FireBallSpawnPoint = wallSpawnPoint; gameNode.AddChild(node); can_cooldown = false; cooldownTimer.Start(); }
private void CheckAndLaunchLaserAttack() { if (_laserLaunched) { return; } EnemyLaser enemyLaserInstance = (EnemyLaser)laserPrefab.Instance(); GetParent().AddChild(enemyLaserInstance); Node2D launchPoint = _launchPoints[0]; enemyLaserInstance.SetGlobalPosition(launchPoint.GetGlobalPosition()); enemyLaserInstance.SetGlobalRotationDegrees(_rotationNode.GetGlobalRotationDegrees()); _currentLaser = enemyLaserInstance; _laserLaunched = true; }
public override void _Ready() { if (!Engine.IsEditorHint() && _shadedNodePath != null) { _shadedNode = GetNode <Node2D>(_shadedNodePath); _shadedNode.Material = Material.Duplicate() as Material; } if (!Engine.IsEditorHint()) { GameEventDispatcher.Instance.Connect(nameof(GameEventDispatcher.EventPlayerInteract), this, nameof(OnPlayerInteract)); } Connect("mouse_entered", this, nameof(OnMouseEntered)); Connect("mouse_exited", this, nameof(OnMouseExited)); Connect("input_event", this, nameof(OnInputEvent)); SetProcess(false); }
public void spawn_new_player() { Node2D main_scene = (Node2D)GetTree().Root.GetNode("Main"); Timer live_time = new Timer(); live_time.Connect("timeout", this, "remove_new_player"); live_time.OneShot = true; live_time.WaitTime = 10; live_time.Name = "Grow_Live_Time"; main_scene.AddChild(live_time); live_time.Start(); KinematicBody2D player = (KinematicBody2D)GetTree().Root.GetNode("Main").GetNode("Player"); PackedScene player_scene = GD.Load <PackedScene>("res://Scenes/Player.tscn"); KinematicBody2D new_player = (KinematicBody2D)player_scene.Instance(); player.AddChild(new_player); new_player.Position = new Vector2(0, 0); GD.Print(live_time.TimeLeft); }
private void HandleAutoMovement() { if (_controllable.Health <= 0) { return; } if (_target is Pickable.Pickable pickable && pickable.PickedUp) { _target = null; } if (_target == null) { _controllable.Velocity = Vector2.Zero; FindTarget(); return; } _controllable.Velocity = _controllable.Position.DirectionTo(_target.Position); }
public override void _Ready() { nodes = new node[gridWidth, gridHeight]; //create Grid [25 x 14] for (int y = 0; y < gridHeight; y++) { for (int x = 0; x < gridWidth; x++) { //create Node Node2D newNode = (Node2D)node.Instance(); newNode.Position = new Vector2((x + 1) * gridNodeWidth, (y + 1) * gridNodeHeight); AddChild(newNode); node nodeInstance = (node)newNode; nodes[x, y] = nodeInstance; nodeInstance.posGrid = new Vector2(x, y); } } }
static void addBasicVariable(int minI, int minJ, double[] supply, double[] demand, Node previousUMinI, Node previousVMinJ, Node UHead) { double T; if (Math.Abs(supply[minI] - demand[minJ]) <= _epsilon * _maximumWeight) { T = supply[minI]; supply[minI] = 0; demand[minJ] -= T; } else if (supply[minI] < demand[minJ]) { T = supply[minI]; supply[minI] = 0; demand[minJ] -= T; } else { T = demand[minJ]; demand[minJ] = 0; supply[minI] -= T; } _isExchange[minI, minJ] = true; _endExchange.Value = T; _endExchange.I = minI; _endExchange.J = minJ; _endExchange.NextC = _exchangeRows[minI]; _endExchange.NextR = _exchangeColumns[minJ]; _exchangeRows[minI] = _endExchange; _exchangeColumns[minJ] = _endExchange; _endExchange = _endExchange.Next; if (supply[minI] == 0 && UHead.Next.Next != null) { previousUMinI.Next = previousUMinI.Next.Next; } else { previousVMinJ.Next = previousVMinJ.Next.Next; } }
public override void _Process(float delta) { Node2D rayCasts = jelly.GetNode <Node2D>("RayCasts"); if (Input.IsActionPressed("ui_accept")) { Vector2 dirJump = Vector2.Zero; foreach (Node n in rayCasts.GetChildren()) { RayCast2D rayCast = (RayCast2D)n; if (rayCast.IsColliding()) { dirJump -= rayCast.CastTo; } } dirJump = dirJump.Rotated(rayCasts.GlobalRotation).Normalized(); jelly.center.ApplyCentralImpulse(dirJump * 120); } }
public GodotArmature BuildArmatureNode(string armatureName, string dragonBonesName = "", string skinName = "", string textureAtlasName = "", Node2D node = null) { _displayNode = node; var armature = BuildArmature(armatureName, dragonBonesName, skinName, textureAtlasName); // its call _BuildArmature => _BuildBones => _BuildSlots if (armature == null) { return(null); } _dragonBones.clock.Add(armature); var armatureDisplay = armature.display as Node2D; var armatureNode = armatureDisplay?.GetNode <GodotArmature>(armatureName); return(armatureNode); }
private Node SpawnNodeScene(string ScenePath, string ParentPath, string NodeName, int NetworkMaster, Vector3 SpawnPos) { MDLog.Log(LOG_CAT, MDLogLevel.Debug, $"Spawning Node. Scene: {ScenePath} ParentPath: {ParentPath} Name: {NodeName} Master: {NetworkMaster}"); Node Parent = GetNodeOrNull(ParentPath); if (Parent == null) { MDLog.Error(LOG_CAT, $"Could not find Parent with path: {ParentPath}"); return(null); } PackedScene Scene = LoadScene(ScenePath); if (Scene == null) { return(null); } Node NewNode = Scene.Instance(); NewNode.Name = NodeName; NewNode.SetNetworkMaster(NetworkMaster); NetworkedScenes.Add(NewNode, ScenePath); OrderedNetworkedNodes.Add(NewNode); Node2D NewNode2D = NewNode as Node2D; Spatial NewNodeSpatial = NewNode as Spatial; if (NewNode2D != null) { NewNode2D.Position = SpawnPos.To2D(); } else if (NewNodeSpatial != null) { NewNodeSpatial.Translation = SpawnPos; } Parent.AddChild(NewNode); OnNetworkNodeAdded(NewNode); return(NewNode); }
public override void Enter() { DestroyHook = false; player.Velocity *= 0.5f; player.MoveAndSlide(player.Velocity); reticule = new Node2D(); reticuleSpr = new Sprite(); reticule.SetName("Reticule"); reticule.SetPosition(64 * (player.GetGlobalMousePosition() - player.GetGlobalPosition()).Normalized()); reticuleSpr.SetTexture((Texture)ResourceLoader.Load("res://Player/HookReticule.png")); reticuleSpr.SetRotation(Mathf.PI / 2 + reticule.GetPosition().Angle()); player.AddChild(reticule); reticule.AddChild(reticuleSpr); base.Enter(); }
public override void _Ready() { projectilesNode = GetNode <Node2D>("Projectiles"); stageNode = GetNode <Node2D>("Stage"); Entities = GetNode <Node2D>("Entities"); MainCamera = GetNode <TransitionCamera>("MainCamera"); MessageNode = GetNode <Node2D>("UILayer/MessageNode"); MessageLabel = GetNode <Label>("UILayer/MessageNode/MessageLabel"); FramedMessage = GetNode <FramedMessage>("UILayer/FramedMessage"); MoonHunter.Instance.RegisterGameplayScreen(this); SetupStage(CurrentLevel, Background, true); if (!SoundManager.Instance.GameAudioPlayer.Playing) { SoundManager.Instance.StartGameAudioPlayer.Stop(); SoundManager.Instance.GameAudioPlayer.Play(); } }
public override void _PhysicsProcess(float delta) { CurrentVelocity = MoveAndSlide(CurrentVelocity.LinearInterpolate(Velocity, Damping * delta)); if (GetSlideCount() > 0) { Node2D N = Explode.Instance() as Node2D; N.Position = GlobalPosition; GetTree().Root.GetChild(0).AddChild(N); QueueFree(); return; } //Clamp Position Rect2 Rct = GetViewport().GetVisibleRect(); Position = new Vector2(Mathf.Clamp(Position.x, Rct.Position.x, Rct.Size.x), Mathf.Clamp(Position.y, Rct.Position.y, Rct.Size.y)); }
public override void _Ready() { Crosshair = GetNode <TextureRect>("CLayer/CrossCenter/TextureRect"); CooldownBar = GetNode <ProgressBar>("CLayer/CooldownCenter/VBox/CooldownBar"); HealthBar = GetNode <ProgressBar>("CLayer/HealthVBox/HealthHBox/HealthBar"); ChunkInfoLabel = GetNode <Label>("CLayer/ChunkInfo"); PlayerPositionLabel = GetNode <Label>("CLayer/PlayerPosition"); FPSLabel = GetNode <Label>("CLayer/FPSLabel"); DamageIndicatorRoot = GetNode <Node2D>("CLayer/DamageIndicatorRoot"); NickLabelLayer = GetNode <CanvasLayer>("NickLabelLayer"); GetNode <Label>("CLayer/VersionLabel").Text = $"Version: {Game.Version}"; GetTree().Connect("screen_resized", this, nameof(OnScreenResized)); HotbarUpdate(); this.CallDeferred(nameof(OnScreenResized)); Show(); //To make sure we catch anything which might be wrong after hide then show }
public override bool fire(Node2D source, Node2D target) { Timer timer = (Timer)GetNode("WeaponTimer"); if (CanShoot && Ammo != 0) { CanShoot = false; Ammo -= 1; EmitSignal(nameof(AmmoChangedSignal), Ammo * 100 / MaxAmmo); laserRay.setSource((Tank)source); laserRay.setIsCasting(true); timer.Start(); return(true); } return(false); }
private void _emit(Node2D enemy_object, int n = 0) { if (!enemyScenes.ContainsKey(enemy_object)) { return; } var bullet_scene = enemyScenes[enemy_object]; var queue = bullets[bullet_scene]; int limit = bulletsLimit[bullet_scene]; //GD.Print($"emit {enemy_object.Position} {n} {queue.Count} {OS.GetTicksMsec()}"); BaseBullet bullet; if (queue.Count >= limit) { bullet = queue.Dequeue(); } else if (queue.Count == 0 || queue.Peek().Visible) { bullet = bulletScenes[bullet_scene].Instance() as BaseBullet; bullet.GDArea = GetParent <GDKnyttArea>(); AddChild(bullet); } else { bullet = queue.Dequeue(); } bullet.GlobalPosition = enemy_object.GlobalPosition; bullet.Enabled = true; bullet.Visible = true; var enemy_parent = enemy_object.GetParent <Node2D>(); if (enemy_parent is CustomObject) { enemy_parent = enemy_parent.GetParent <Node2D>(); } bullet.ZIndex = enemy_parent is GDKnyttObjectLayer ? enemy_parent.ZIndex - 1 : enemy_object.ZIndex; initEvents[enemy_object](bullet, n); queue.Enqueue(bullet); }
public override void _Process(float delta) { var g = GetTree().GetNodesInGroup("Player"); Node2D[] p = new Node2D[g.Count]; g.CopyTo(p, 0); p = p.Where(n => (n as Knight).Health > 0).ToArray(); p = p.Where(n => n.GlobalPosition.DistanceTo(GlobalPosition) < 40).ToArray(); if (p.Any() && AttackCooldown.TimeLeft == 0 && Health > 0) { var k = p.FirstOrDefault(); Sprite.FlipH = k.GlobalPosition < GlobalPosition; AttackCooldown.Start(3f); ShootTimer.Start(1.5f); Animation.Play("A"); } }
public override void _Ready() { _items = GetNode <Node2D>("AnimatedSprite/Items"); _pointsLabel = GetNode <Label>("Points"); _animatedSprite = GetNode <AnimatedSprite>("AnimatedSprite"); _resetAnimationTimer = GetNode <Timer>("Timers/ResetAnimation"); _resetAnimationTimer.Connect("timeout", this, nameof(ResetAnimation)); if (EmptyOrder) { return; } _pointsLabel.Show(); SelectRandomPoints(); SetupItemPosition(); }
private void SetupGameObjects() { // setup packed scenes used to spawn multiple objects from the same textures _enemyObject = (PackedScene)ResourceLoader.Load("res://Scenes/Objects/Enemy.tscn"); _bulletObject = (PackedScene)ResourceLoader.Load("res://Scenes/Objects/Bullet.tscn"); _explosionObject = (PackedScene)ResourceLoader.Load("res://Scenes/Objects/Explosion.tscn"); // get containers _bullets = GetNode("GameCanvas/Bullets"); _enemies = GetNode("GameCanvas/Enemies"); _explosions = GetNode("GameCanvas/Explosions"); // get ui _scoreUi = (Node2D)GetNode("GameCanvas/ScoreUI"); _healthbar = (Node2D)GetNode("GameCanvas/Healthbar"); _statusPanel = (StatusPanel)GetNode("GameCanvas/StatusPanel"); _statusPanel.Connect("ResetGame", this, nameof(StartGame)); // sounds _hitSound = (AudioStreamPlayer)GetNode("Audio/Hit"); _crashSound = (AudioStreamPlayer)GetNode("Audio/Crash"); _laserSound = (AudioStreamPlayer)GetNode("Audio/Laser"); _explosionSound = (AudioStreamPlayer)GetNode("Audio/Explosion"); // connect the ship signal to a method inside our game scene, this would allow us to spawn bullets // into the scene after we press spacebar. Allowing us to keep our code as separated as possible. Also // allowing us to have bullets interact with other things like enemies in our case. _ship = (Ship)GetNode("GameCanvas/Ship"); _ship.Connect("Damaged", this, nameof(ShipHit)); _ship.Connect("Destroyed", this, nameof(ShipDestroyed)); _ship.Connect("WeaponDischarged", this, nameof(SpawnBullet)); // setup monster spawner timer _enemySpawnTimer = (Timer)GetNode("GameCanvas/EnemySpawnTimer"); _enemySpawnTimer.Connect("timeout", this, nameof(SpawnEnemies)); _formationTimer = (Timer)GetNode("GameCanvas/FormationTimer"); _formationTimer.Connect("timeout", this, nameof(SetNewFormation)); _statusPanel.ShowStartGamePanel(); }
void DrawAllComputers(Vector2[] locatons) { foreach (var location in locatons) { Node2D newComputer = (Node2D)computer.Instance(); newComputer.Position = PrepareLocation(location); PCGroup.AddChild(newComputer); } //for (int i = 0; i < collumnsCount; i++) // { // for (int j = 0; j < rowsCount; j++) // { // Node2D newComputer = (Node2D)computer.Instance(); // newComputer.Position = new Vector2(margin + koefX * i, margin + koefY * j); // PCGroup.AddChild(newComputer); // } // } }
void CreateLevel(int size) { //reset everything nextPathId = 1; map = null; if (board != null) { RemoveChild(board); board.QueueFree(); } board = new Node2D(); AddChild(board); HideCursor(); map = new HexMap(size); map.Initialize(c => new CellInfo(c, AddBoardCell(c))); spawnCoord = new HexCoord(size * 2, 0); SpawnTile(); }
public override void _Ready() { Controller = new PlayerController(this); Sprite = (AnimatedSprite)GetNode("Sprite"); RayPivot = (Node2D)GetNode("RayPivot"); Clock = (RichTextLabel)GetNode("UI/ControlUI/Clock"); MessageLabel = (RichTextLabel)GetNode("UI/ControlUI/Message"); MessageLabel.BbcodeText = ""; CurrencyLabel = (RichTextLabel)GetNode("UI/ControlUI/Currency"); Currency += 5; Inventory = new Inventory(); Inventory.Items.Add(Database <Item> .Get("Tools\\BasicHoe")); Inventory.Items.Add(Database <Item> .Get("Tools\\BasicWateringCan")); TimeNode = (DayNight)GetNode("DayNight"); }
public override void Act() { if (agent.GetActionName() == actionName) { float[] f = agent.GetActionArgAsFloatArray(); fx = f[0]; fy = f[1]; if (is2D) { Node2D body = agent.GetBody() as Node2D; body.Translate(new Vector2(fx, fy)); } else { fz = f[2]; Spatial sp = agent.GetBody() as Spatial; sp.Translation = sp.Translation + new Vector3(fx, fy, fz); } } }
public void OnSwordHitBoxBodyEnter(Godot.Object body) { if (body == player) { return; } if (body is IPushable) { ((IPushable)body).Push(player.Position.DirectionTo(((Node2D)body).Position), lightAttackPushingForce); } if (body is IDamageable) { Node2D instance = blood.Instance <Node2D>(); ((Node2D)body).AddChild(instance); Node2D node = (Node2D)body; ((IDamageable)body).ApplyDamage((Node)this, lightAttackDamage); } }
public override void _Ready() { _rand.Randomize(); _hud = GetNode <HUD>("HUD"); _arena = GetNode <Arena>("../Arena"); _wizzard = GetNode <Wizzard>("../Friend/Wizzard"); _playerSpawner = GetNode <Node2D>("PlayerSpawner"); _musicPlayer = GetNode <AudioStreamPlayer>("MusicPlayer"); _player = SpawnPlayer(); _monsterSpawnTimer = new Timer { OneShot = false, Autostart = true, WaitTime = 2f }; _monsterSpawnTimer.Connect("timeout", this, nameof(SpawnMonster)); AddChild(_monsterSpawnTimer); _musicPlayer.Stream = _dungeonMusic; _musicPlayer.Play(); }
void CreateGrid() { Grid = new Node2D[gridSizeX, gridSizeY]; worldBottomLeft = Vector3.zero - Vector3.right * gridWorldSize.x / 2 - Vector3.up * gridWorldSize.y / 2; for (int x = 0; x < gridSizeX; x++) { for (int y = 0; y < gridSizeY; y++) { Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.up * (y * nodeDiameter + nodeRadius); Grid[x, y] = new Node2D(false, worldPoint, x, y); //if (obstaclemap.HasTile(obstaclemap.WorldToCell(Grid[x, y].worldPosition))) //Grid[x, y].SetObstacle(true); //else Grid[x, y].SetObstacle(false); } } }
public void AddAgent(Agent agent) { if (!_agents.ContainsKey(agent.GetUnitName())) { Node2D agentMarker = (Node2D)_agentMarker.Duplicate(); agentMarker.Name = agent.GetUnitName() + "_marker"; agentMarker.Modulate = Team.TeamColor[(int)agent.GetCurrentTeam()]; AddChild(agentMarker); agentMarker.Show(); // Add agent to dictonary _agents.Add(agent.GetUnitName(), agent); // Add marker to dictionary _agentMarkers.Add(agent.GetUnitName(), agentMarker); } }
/// <summary> /// Handle new instances /// </summary> /// <param name="node"></param> private void OnInstanceCreated(Node node) { Node2D target = node as Node2D; target.Position = Position; target.RotationDegrees = RotationDegrees; target.Scale = Scale; Instances.Add(target); target.Connect(nameof(EnemyController.NodeDeleted), this, nameof(OnNodeDeleted)); if (TargetInstance == null) { GetParent().CallDeferred("add_child", target); } else { GetNode(TargetInstance).CallDeferred("add_child", target); } }
void Update() { if (screenHeight != Screen.height || screenWidth != Screen.width) { UpdateSpriteGrid(); screenHeight = Screen.height; screenWidth = Screen.width; } dirty.Clear(); RaycastHit hitInfo; if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hitInfo)) { var match = nameRegex.Match(hitInfo.transform.name); var i = System.Convert.ToInt32(match.Groups["i"].Value); var j = System.Convert.ToInt32(match.Groups["j"].Value); var hoveredNode = grid[i, j]; if (Input.GetMouseButtonDown(0)) { nodeToCopy = null; if (hoveredNode == start) { if (path != null) { foreach (Node2D node in path) { dirty.Add(node); } } else { dirty.Add(start); } start = null; path = null; } else if (hoveredNode == end) { if (path != null) { foreach (Node2D node in path) { dirty.Add(node); } } else { dirty.Add(end); } end = null; path = null; } else if (start == null) { start = hoveredNode; dirty.Add(hoveredNode); } else if (end == null) { end = hoveredNode; dirty.Add(hoveredNode); } else { nodeToCopy = hoveredNode; } } else if (Input.GetMouseButton(0)) { if (nodeToCopy != null && hoveredNode.Weight != nodeToCopy.Weight) { hoveredNode.Weight = nodeToCopy.Weight; dirty.Add(hoveredNode); } } else if (Input.GetMouseButtonUp(0) && hoveredNode == nodeToCopy) { if (hoveredNode.Weight == WallWeight) { hoveredNode.Weight = WaterWeight; } else if (hoveredNode.Weight == WaterWeight) { hoveredNode.Weight = GrassWeight; } else if (hoveredNode.Weight == GrassWeight) { hoveredNode.Weight = DefaultWeight; } else { hoveredNode.Weight = WallWeight; } dirty.Add(hoveredNode); } } // repaint if (dirty.Count > 0) { if (path != null) { foreach (Node2D node in path) { tiles[node.X, node.Y].color = GetNodeColor(node); } } foreach (var dirtyNode in dirty) { tiles[dirtyNode.X, dirtyNode.Y].color = GetNodeColor(dirtyNode); } if (start != null && end != null) { Chrono.Run(searchEngine.ToString(), () => { path = pathFinder.FindPath(start, end); }); if (searchEngine == Engine.Fringe) ResearchData.FringeMem = path.Count(); else ResearchData.AStarMem = path.Count(); Debug.LogFormat("{0} - Path Size: {1}, Path Cost: {2}, Visited Nodes {3}", searchEngine, path.Count(), pathFinder.PathCost, pathFinder.VisitedNodes); foreach (Node2D node in path) { if (node == start || node == end) { continue; } tiles[node.X, node.Y].color = Color.magenta + Color.white * .5f; } } } // repaint path }
/// <summary> /// Gets distance from node A to node B /// </summary> /// <param name="a">node A</param> /// <param name="b">node B</param> /// <returns>Distance between node A and node B</returns> protected override double Distance(Node2D a, Node2D b) { var xd = a.X - b.X; var yd = a.Y - b.Y; return MathExtensions.NearestInt(Math.Sqrt(xd * xd + yd * yd)); }
/// <summary> /// Creates a new instance of geographical location from 2D node /// </summary> /// <param name="node">node to convert to geo location</param> public GeoLocation(Node2D node) { Latitude = CalcGeoValue(node.X); Longitude = CalcGeoValue(node.Y); }
/// <summary> /// Gets distance from node A to node B /// </summary> /// <param name="a">node A</param> /// <param name="b">node B</param> /// <returns>Distance between node A and node B</returns> protected override double Distance(Node2D a, Node2D b) { var xd = Math.Abs(a.X - b.X); var yd = Math.Abs(a.Y - b.Y); return Math.Max(MathExtensions.NearestInt(xd), MathExtensions.NearestInt(yd)); }
/// <summary> /// Gets distance from node A to node B /// </summary> /// <param name="a">node A</param> /// <param name="b">node B</param> /// <returns>Distance between node A and node B</returns> protected override double Distance(Node2D a, Node2D b) { var xd = a.X - b.X; var yd = a.Y - b.Y; return Math.Ceiling(Math.Sqrt(xd * xd + yd * yd)); }
/// <summary> /// 与えられた点の座標が円の内部に含まれるかどうか判定する. /// </summary> /// <param name="p">点</param> /// <returns>判定結果</returns> public bool Inside(Node2D p) { double distance_sq = ((p.X - center.X) * (p.X - center.X) + (p.Y - center.Y) * (p.Y - center.Y)); if (distance_sq < radius * radius) { return true; } else { return false; } }