public Intersection_Grid(Spatial.Grids.Grid_Info Grid_Info) { this.grid_info = Grid_Info; grids = new Spatial_Hash_Grid[grid_info.groups]; for (int u = 0; u < grid_info.groups; u++) grids[u] = new Spatial_Hash_Grid(); neutral = grids[(int)Col_Slot.Neutral]; player = grids[(int)Col_Slot.Player]; }
void Start() { if (m_fsm != null) { StateMove stateMove = new StateMove(); StateIdle stateIdle = new StateIdle(); stateIdle.AddTransition(FSMTransition.MOVE, FSMStateId.STATE_MOVE); stateMove.AddTransition(FSMTransition.STOP_MOVE, FSMStateId.STATE_IDLE); m_fsm.AddState(stateIdle); m_fsm.AddState(stateMove); m_fsm.CurrentState = stateIdle; } m_spatial = gameObject.GetComponent<Spatial>(); m_fighter = gameObject.GetComponent<Fightable>(); }
static void Main(string[] args) { try { //Declare an spatial object Spatial spatial = new Spatial(); //Hook the basic event handlers spatial.Attach += new AttachEventHandler(accel_Attach); spatial.Detach += new DetachEventHandler(accel_Detach); spatial.Error += new ErrorEventHandler(accel_Error); //hook the phidget specific event handlers spatial.SpatialData += new SpatialDataEventHandler(spatial_SpatialData); //open the acclerometer object for device connections spatial.open(); //get the program to wait for an spatial device to be attached Console.WriteLine("Waiting for spatial to be attached...."); spatial.waitForAttachment(); //Set the data rate so the events aren't crazy spatial.DataRate = 496; //multiple of 8 //Get the program to wait for user input before moving on so that we can //watch for some events Console.WriteLine("Press any key to end"); Console.Read(); //If user input has been read, we can now terminate the program, so //close the phidget object spatial.close(); //set the object to null to clear it from memory spatial = null; //if no exceptions have been trhown at this point, the program can //terminate safely Console.WriteLine("ok"); } catch (PhidgetException ex) { Console.WriteLine(ex.Description); } }
public static Vector3 GetGlobalPosition(this Spatial spatial) { return(spatial.GlobalTransform.origin); }
public override void _Ready() { RotationNode = (Spatial)GetNode(RotationNodePath); EyeRelief = (RemoteTransform)GetNode(EyeReliefPath); RemoteEyeRelief = (Position3D)EyeRelief.GetNode(EyeRelief.RemotePath); }
// Creates the hexagon or pentagon instance for the tile. private void CreateSceneOnTile(Tile tile, float sphereScale) { bool createMeshForTile = true; decimal tileCenterX = 0; decimal tileCenterY = 0; decimal tileCenterZ = 0; decimal polygonRadius = 0; List <Point> points = tile.boundary; //Calculate the average center point and polygon side length. var lastPoint = points[points.Count - 1]; Vector3 lastPointVector = new Vector3((float)lastPoint.x, (float)lastPoint.y, (float)lastPoint.z); decimal polygonSideLength = 0; foreach (Point point in points) { tileCenterX += point.x / points.Count; tileCenterY += point.y / points.Count; tileCenterZ += point.z / points.Count; Vector3 currentVector = new Vector3((float)point.x, (float)point.y, (float)point.z); polygonSideLength += (decimal)currentVector.DistanceTo(lastPointVector); lastPointVector = currentVector; } polygonSideLength = polygonSideLength / points.Count; //Create the center point var tileCenterPoint = new Vector3((float)tileCenterX, (float)tileCenterY, (float)tileCenterZ); var firstPoint = new Vector3((float)points[0].x, (float)points[0].y, (float)points[0].z); //Get the average polygon radius from center to each point. foreach (Point point in points) { var vector = new Vector3((float)point.x, (float)point.y, (float)point.z); polygonRadius += (decimal)vector.DistanceTo(tileCenterPoint); } polygonRadius = polygonRadius / points.Count; var sphereCenterPoint = new Vector3(0f, 0f, 0f); //Create the debug spheres to go on each tile MeshInstance sphere = (MeshInstance)blueSphereMeshScene.Instance(); sphere.SetTranslation(tileCenterPoint); sphere.SetScale(new Vector3(sphereScale, sphereScale, sphereScale)); this.AddChild(sphere); MeshInstance sphere2 = (MeshInstance)greenSphereMeshScene.Instance(); sphere2.SetTranslation(firstPoint); sphere2.SetScale(new Vector3(sphereScale, sphereScale, sphereScale)); this.AddChild(sphere2); MeshInstance sphere3 = (MeshInstance)greenSphereMeshScene.Instance(); sphere3.SetTranslation((firstPoint - tileCenterPoint) / 2 + tileCenterPoint); sphere3.SetScale(new Vector3(sphereScale, sphereScale, sphereScale)); this.AddChild(sphere3); //Create the tile instance Spatial groundTest = null; if (points.Count == 5) { //GD.Print("Pentagon Radius: " + polygonRadius + ", side length: " + polygonSideLength); //Create instance groundTest = GetRandomPentagon(); if (isPyramid) { //tile.queue_free(); createMeshForTile = false; } } else if (points.Count == 6) { //GD.Print("Hexagon Radius: " + polygonRadius + ", side length: " + polygonSideLength); //Create instance groundTest = GetRandomHexagon(); } else { //GD.Print("Unknown Radius: " + polygonRadius + ", Count: " + points.Count + ", Side Length: " + polygonSideLength); } if (groundTest != null) { if (points.Count == 5 && placedPentagons == 1) { createMeshForTile = false; } //Put the instance on the tile and make it face the center of the sphere //This should be all that is needed but the sections are rotated perpendicular groundTest.LookAtFromPosition(tileCenterPoint, sphereCenterPoint, new Vector3(0f, 1f, 0f)); //Get the local axis of the instance var axis = groundTest.GetTransform().basis.Xform(new Vector3(-1, 0, 0)).Normalized(); //Rotate it to face the center (I have no idea why this is necessary) groundTest.Rotate(axis, (float)(Math.PI / 2.0)); //Get the local axis of the instance var axis2 = groundTest.GetTransform().basis.Xform(new Vector3(0, 1, 0)).Normalized(); //Add ground to world this.AddChild(groundTest); this.hexInstances.Add(groundTest); //Create and convert local point to world point var localOriginalFirstPoint = new Vector3(0, 0, (float)polygonRadius); var worldOriginalFirstPoint = groundTest.ToGlobal(localOriginalFirstPoint); var worldGeneratedFirstPoint = firstPoint; var localGeneratedFirstPoint = groundTest.ToLocal(worldGeneratedFirstPoint); MeshInstance redSphere = (MeshInstance)redSphereMeshScene.Instance(); redSphere.SetTranslation(worldOriginalFirstPoint); redSphere.SetScale(new Vector3(sphereScale, sphereScale, sphereScale)); this.AddChild(redSphere); //World Original First Point works and is correct //Now is there a way I can get the two points and match them up? var angleCalcOriginalPoint = worldOriginalFirstPoint - tileCenterPoint; var angleCalcFirstPoint = firstPoint - tileCenterPoint; var angle = angleCalcFirstPoint.AngleTo(angleCalcOriginalPoint); var angle2 = new Vector2(localGeneratedFirstPoint.x, localGeneratedFirstPoint.z).AngleTo(new Vector2(localOriginalFirstPoint.x, localOriginalFirstPoint.z)); var axis3 = groundTest.GetTransform().basis.Xform(new Vector3(0, 1, 0)); if (points.Count == 5) { angle2 += (float)Math.PI / 4; } //angleCalcFirstPoint. //Rotate it to match up with other parts of the sphere groundTest.Rotate(axis3, angle2); var newWorldPoint = groundTest.ToGlobal(localOriginalFirstPoint); //GD.Print("Difference: " + (worldGeneratedFirstPoint - newWorldPoint)); } if (createMeshForTile) { CreateMeshForTile(tile, sphereScale); } }
private Spatial _Board; //para poner todos los suelos instanciados // Called when the node enters the scene tree for the first time. public override void _Ready() { _Board = (Spatial)GetTree().GetNodesInGroup("Board")[0]; //busco el nodo para guardar los suelos que van a ser creados GD.Randomize(); //creo una semilla aleatoria para que la aleatoriedad siempre sea distinta }
public override void _Ready() { _offset = GetTranslation(); _follow = (Spatial)GetNode(FollowNode); }
Node ExtractNodeBranch(GameObject go) { // TODO Detect if go is a prefab with PrefabUtility var componentNodes = new List <Node>(); Component[] components = go.GetComponents <Component>(); NodeCategory rootCategory = DetectCategory(go); Node rootNode = null; Rigidbody2D promoteRigidBody2D = null; float rescale2d = 1f; int scriptCount = 0; Script script = null; Dictionary <string, object> scriptVariables = null; foreach (var cmp in components) { Node node = null; if (cmp is SpriteRenderer) { var src = (SpriteRenderer)cmp; var dst = new Sprite(); node = dst; dst.selfModulate = src.color; if (src.sprite != null) { dst.texture = Util.Cast <Texture>(ConvertUnityAsset(src.sprite)); rescale2d = src.sprite.pixelsPerUnit; } } else if (cmp is Rigidbody2D) { // In Godot, bodies work best as root promoteRigidBody2D = (Rigidbody2D)cmp; } else if (cmp is Collider2D) { // TODO Proper CollisionShape2D node = new CollisionShape2D(); } else if (cmp is Camera) { var cam = (Camera)cmp; if ((rootCategory == NodeCategory.Node2D || _hint2D) && cam.orthographic) { node = new Camera2D(); } else { // TODO 3D Camera } } else if (cmp is MonoBehaviour) { var mb = (MonoBehaviour)cmp; var s = ConvertScript(mb); if (s != null) { if (scriptCount == 0) { script = s; scriptVariables = GetScriptVariables(mb); } else { node = new Node(); node.name = cmp.GetType().Name; node.script = s; node.scriptVariables = GetScriptVariables(mb); } ++scriptCount; } } else { // TODO more } if (node != null) { componentNodes.Add(node); } } if (rootCategory == NodeCategory.Node2D) { Node2D node2d = null; if (promoteRigidBody2D != null) { if (promoteRigidBody2D.isKinematic) { var n = new KinematicBody2D(); node2d = n; } else { var n = new RigidBody2D(); node2d = n; } } else { if (componentNodes.Count == 1 && componentNodes[0] is Node2D && !(script != null && componentNodes[0].script != null)) { // If there is only one component node, don't create a root node with a single child // TODO Merge transform? Not sure if relevant because this is components node2d = (Node2D)componentNodes[0]; componentNodes.Clear(); } else { node2d = new Node2D(); } } node2d.position = go.transform.position * rescale2d; node2d.position.y *= -1f; // TODO Invert Y properly // TODO Select pivot //node2d.position.y = Screen.height - node2d.position.y; node2d.scale = go.transform.localScale; // TODO Is eulerAngles in degrees or radians?? node2d.rotation = go.transform.rotation.eulerAngles.z; node2d.visible = go.activeSelf; rootNode = node2d; } else if (rootCategory == NodeCategory.Control) { var control = new Control(); control.visible = go.activeSelf; rootNode = control; } else if (rootCategory == NodeCategory.Spatial) { var spatial = new Spatial(); rootNode = spatial; } else { rootNode = new Node(); } if (rootNode != null) { rootNode.name = go.name; if (script != null) { rootNode.script = script; } if (scriptVariables != null) { rootNode.scriptVariables = scriptVariables; } foreach (var child in componentNodes) { if (child.name == null) { child.name = child.GetType().Name; } rootNode.AddChild(child); } } // Children Transform transform = go.transform; for (int i = 0; i < transform.childCount; ++i) { GameObject childGo = transform.GetChild(i).gameObject; Node childNode = ExtractNodeBranch(childGo); rootNode.AddChild(childNode); } return(rootNode); }
// Called when the node enters the scene tree for the first time. public override void _Ready() { parent = (Spatial)GetParent().GetParent().GetParent(); }
private void Form1_Load(object sender, EventArgs e) { p = new Pipeline(); //add some initial points p.addPoint(new Vector3(0, 0, 0), Brushes.Black); p.addPoint(new Vector3(1, 0, 0), Brushes.Black); p.addPoint(new Vector3(0, 1, 0), Brushes.Black); p.addPoint(new Vector3(0, 0, -1), Brushes.Black); p.addPoint(new Vector3(0, 0, 0), Brushes.Black); p.addPoint(new Vector3(0, 0, 0), Brushes.Black); p.indexBuffer.AddRange(new int[] { 0, 1 }); p.indexBuffer.AddRange(new int[] { 0, 2 }); p.indexBuffer.AddRange(new int[] { 0, 3 }); p.indexBuffer.AddRange(new int[] { 0, 4 }); p.indexBuffer.AddRange(new int[] { 0, 5 }); p.lineColors.AddRange(new Pen[] { Pens.Black, Pens.Black, Pens.Black, Pens.Red, Pens.Green }); //rotation speed rots = new Vector3(0, 0.01, 0); Vector3 initialRots = new Vector3(0, 0, 0); Matrix3x3 rotMatrix = new Matrix3x3(); rotMatrix.matrix[0, 0] = 1; rotMatrix.matrix[1, 0] = 0; rotMatrix.matrix[2, 0] = 0; rotMatrix.matrix[0, 1] = 0; rotMatrix.matrix[1, 1] = 1; rotMatrix.matrix[2, 1] = 0; rotMatrix.matrix[0, 2] = 0; rotMatrix.matrix[1, 2] = 0; rotMatrix.matrix[2, 2] = 1; rotMatrix = Math3D.nextRotMatrix2(rotMatrix, initialRots); p.rotMatrix = rotMatrix; origin = new Point(pictureBox1.Width / 2, pictureBox1.Height / 2); Math3D.RotatePoints(p.rotMatrix, p.vertexBuffer, p.originalVertices); pictureBox1.Image = p.Draw(origin, zoom); trackBar4.Value = zoom; spatial = new Spatial(); spatial.Attach += new Phidgets.Events.AttachEventHandler(spatial_Attach); spatial.Detach += new Phidgets.Events.DetachEventHandler(spatial_Detach); spatial.SpatialData += new Phidgets.Events.SpatialDataEventHandler(spatial_SpatialData); spatial.open(); }
static void SpatialInitialization() { spatial = new Spatial(); spatial.Attach += new AttachEventHandler(accel_Attach); spatial.Detach += new DetachEventHandler(accel_Detach); spatial.Error += new ErrorEventHandler(accel_Error); spatial.SpatialData += new SpatialDataEventHandler(spatial_SpatialData); spatial.open(); Console.WriteLine("Waiting for spatial to be attached...."); spatial.waitForAttachment(); // spatial.DataRate = 496; //multiple of 80 spatial.DataRate = 240; //multiple of 80 }
static void SpatialClose() { spatial.close(); spatial = null; Console.WriteLine("ok"); }
//initalize the phidget device and link the event handler code private void Form1_Load(object sender, EventArgs e) { _assembly = Assembly.GetExecutingAssembly(); _imageStream = _assembly.GetManifestResourceStream("Spatial_full.1056_0_Top.png"); spatialImage = new Bitmap(_imageStream); int newWidth = (int)((double)spatialImage.Width * ((double)compassView.Height / (double)spatialImage.Height) * 0.6); int newHeight = (int)((double)compassView.Height * 0.6); spatialImage = new Bitmap(spatialImage, newWidth, newWidth); initAccelGraph(); initGyroGraph(); initMagFieldGraph(); initCompassBearingGraph(); //Phidget.enableLogging(Phidget.LogLevel.PHIDGET_LOG_INFO, null); spatial = new Spatial(); spatial.Attach += new AttachEventHandler(spatial_Attach); spatial.Detach += new DetachEventHandler(spatial_Detach); spatial.Error += new Phidgets.Events.ErrorEventHandler(spatial_Error); spatial.SpatialData += new SpatialDataEventHandler(spatial_SpatialData); openCmdLine(spatial); }
public Brain(Actor actor, Spatial eyes = null) { this.actor = actor; this.eyes = eyes; }
public static Vector2 GetMousePosition(Spatial spat) { return(spat.GetViewport().GetMousePosition()); }
/// <summary> /// Initializes and instance of class <see cref="TransformLerper"/> /// </summary> /// <param name="spatial"></param> public TransformLerper(Spatial spatial) { this._spatial = spatial; }
private void StartButton_Click(object sender, EventArgs e) { StartButton.Enabled = false; try { recordLength = System.Convert.ToInt32(timeTextBox.Text.ToString()); } catch (Exception _Exception) { messageTextBox.Text = _Exception.ToString(); return; } if (recordLength <= 0) { messageTextBox.Text = "Please input a valid record time"; return; } DateTime CurrTime = DateTime.Now; String format = "MMM-ddd-d-HH-mm-ss-yyyy"; prefix = CurrTime.ToString(format); String newPath = System.IO.Path.Combine(prefix); System.IO.Directory.CreateDirectory(newPath); // Phidgets Sensor phidgets = phidgetsCheckBox.Checked; if (phidgets) { // Phidgets Sensor spatial = new Spatial(); //Hook the basic event handlers spatial.Attach += new AttachEventHandler(accel_Attach); spatial.Detach += new DetachEventHandler(accel_Detach); spatial.Error += new Phidgets.Events.ErrorEventHandler(accel_Error); //hook the phidget specific event handlers spatial.SpatialData += new SpatialDataEventHandler(spatial_SpatialData); //open the acclerometer object for device connections spatial.open(); //get the program to wait for an spatial device to be attached messageTextBox.Text += "Waiting for spatial to be attached...."; spatial.waitForAttachment(); //Set the data rate so the events aren't crazy spatial.DataRate = 496; //multiple of 8 String phidgetTimestamp = System.IO.Path.Combine(newPath, prefix + "-phidget.txt"); twPhidgetTimestamp = new StreamWriter(phidgetTimestamp); } // GPS if (gpsCheckBox.Checked == true) { String gpsFileName = System.IO.Path.Combine(newPath, prefix + "-gps.txt"); readGPS = new ReadGPS("COM" + gpsCom.Text, gpsFileName); readGPS.start(); } // Color firstColorFrame = true; String colorFileName = System.IO.Path.Combine(newPath, prefix + "-color.avi"); String colorTimestamp = System.IO.Path.Combine(newPath, prefix + "-color.txt"); aviColorManager = new AviManager(colorFileName, false); twColorTimestamp = new StreamWriter(colorTimestamp); // Depth rawDepth = rawDepthCheckBox.Checked; firstDepthFrame = true; String depthFileName; if (rawDepth) { depthFileName = System.IO.Path.Combine(newPath, prefix + "-depth.data"); rawDepthBinaryWriter = new BinaryWriter(File.OpenWrite(depthFileName)); } else { depthFileName = System.IO.Path.Combine(newPath, prefix + "-depth.avi"); aviDepthManager = new AviManager(depthFileName, false); } String depthTimestamp = System.IO.Path.Combine(newPath, prefix + "-depth.txt"); twDepthTimestamp = new StreamWriter(depthTimestamp); kinect.VideoFrameReady += new EventHandler<ImageFrameReadyEventArgs>(kinect_VideoFrameReady); kinect.DepthFrameReady += new EventHandler<ImageFrameReadyEventArgs>(kinect_DepthFrameReady); kinect.VideoStream.Open(ImageStreamType.Video, 2, ImageResolution.Resolution640x480, ImageType.Color); kinect.DepthStream.Open(ImageStreamType.Depth, 2, ImageResolution.Resolution640x480, ImageType.Depth); // Kinect Audio String kinectAudioFileName = System.IO.Path.Combine(newPath, prefix + "-kinect-audio.wav"); String kinectAudioTimestamp = System.IO.Path.Combine(newPath, prefix + "-kinect-audio.txt"); kinectAudioRecordProcess = new System.Diagnostics.Process(); //p.StartInfo.WorkingDirectory = @"C:\whatever"; kinectAudioRecordProcess.StartInfo.FileName = @"AudioCaptureRaw.exe"; kinectAudioRecordProcess.StartInfo.CreateNoWindow = true; kinectAudioRecordProcess.StartInfo.Arguments = recordLength + " " + kinectAudioFileName + " " + kinectAudioTimestamp; kinectAudioRecordProcess.Start(); // Headset Audio if (headsetAudioCheckBox.Checked == true) { String headsetAudioFileName = System.IO.Path.Combine(newPath, prefix + "-headset-audio.wav"); String headsetAudioTimestamp = System.IO.Path.Combine(newPath, prefix + "-headset-audio.txt"); headsetAudio = new HeadsetAudio("Shure Digital", headsetAudioFileName); tw = new StreamWriter(headsetAudioTimestamp); CurrTime = DateTime.Now; tw.WriteLine(CurrTime.ToString("yyyy-MM-dd HH:mm:ss.fffffff")); headsetAudio.start(); tw.Close(); } this.startTime = DateTime.Now; messageTextBox.Text = "Started"; this.timer = new System.Windows.Forms.Timer(); this.timer.Enabled = true; this.timer.Interval = 1000; this.timer.Tick += new System.EventHandler(this.timer_Tick); // one channel audio record //audioRecord = true; //recordAudioThread = new Thread(new ThreadStart(recordAudio)); //recordAudioThread.Start(); }
public SpatialVisibilityHandler(Spatial spatial) { this.spatial = spatial; }
void Cleanup() { RemoveChild(ZoneNode); ZoneNode = null; }
public override void Update() { Entity player = WatchedComponents.FirstOrDefault()?.Owner; if (player == null) { return; } Spatial playerSp = player.Components.Get <Spatial>(); if (playerSp == null) { return; } foreach (SentryAI sentry in WatchedComponents.Where(c => c is SentryAI && c.Owner.Active)) { if (sentry.ActionTime > 0) { sentry.ActionTime--; } if ((sentry.Owner.Components.Get <Health>()?.CurrentHealth ?? 1) <= 0) { continue; } Spatial sp = sentry.Owner.Components.Get <Spatial>(); Physical phys = sentry.Owner.Components.Get <Physical>(); if (sp == null || phys == null) { continue; } bool inRange = (sp.Position - playerSp.Position).Magnitude < sentry.FollowDistance; if (sentry.Action == SentryAction.Throw && sentry.ActionTime == 30) { Vector2D velocity = new Vector2D(); double targetTime = 0.8; velocity.X = (playerSp.Position.X - sp.Position.X) / targetTime; velocity.Y = ((playerSp.Position.Y - sp.Position.Y - 4) + (362 * targetTime * targetTime) / 2) / targetTime; velocity = velocity.Normalize() * Math.Min(velocity.Magnitude, 256); Owner.Entities.Add(new Projectile(sentry.Owner, sp.Position + new Vector2D(0, 4), velocity)); } if (!sentry.OnGround) { continue; } if (inRange && sentry.ActionTime == 0) { //Choose action double distance = (playerSp.Position - sp.Position).Magnitude; int[] weights = { 1, 2, 3 }; if (distance > 64) { weights[0] = 10; } else if (distance < 48) { weights[1] = 6; } else { weights[2] = 4; } SentryAction next; int pick = Random.Next(weights[0] + weights[1] + weights[2]); if (pick < weights[0]) { next = SentryAction.Charge; } else if (pick < weights[0] + weights[1]) { next = SentryAction.Dodge; } else { next = SentryAction.Throw; } sentry.Action = next; switch (next) { case SentryAction.Charge: { phys.Velocity = new Vector2D(128 * Math.Sign(playerSp.Position.X - sp.Position.X), 64); sentry.ActionTime = Random.Next(30, 60); break; } case SentryAction.Dodge: { phys.Velocity = new Vector2D(-64 * Math.Sign(playerSp.Position.X - sp.Position.X), 64); sentry.ActionTime = Random.Next(30, 60); break; } case SentryAction.Throw: { sentry.ActionTime = 80; break; } } } } }
public void StartWorld() { Input.SetMouseMode(Input.MouseMode.Visible); PackedScene main = (PackedScene)ResourceLoader.Load("res://Maps/lastresort_b5.tscn"); Spatial inst = (Spatial)main.Instance(); Initial of = GetNode("/root/Initial") as Initial; of.AddChild(inst); Spatial entitySpawns = GetNode("/root/Initial/Map/QodotMap/Entity Spawns") as Spatial; Godot.Collections.Array ents = entitySpawns.GetChildren(); foreach (Spatial ent in ents) { Godot.Collections.Dictionary fields = ent.Get("properties") as Godot.Collections.Dictionary; if (fields != null) { foreach (DictionaryEntry kvp in fields) { if (kvp.Key.ToString().ToLower().Contains("classname")) { switch (kvp.Value.ToString().ToLower()) { case "info_player_start": foreach (DictionaryEntry kvp2 in fields) { switch (kvp2.Key.ToString().ToLower()) { case "allowteams": string team = kvp2.Value.ToString().ToLower(); if (team.Contains("blue")) { spawnsTeam1.Add(ent); } if (team.Contains("red")) { spawnsTeam2.Add(ent); } break; } } break; } } } } } Spatial triggers = GetNode("/root/Initial/Map/QodotMap/Triggers") as Spatial; Godot.Collections.Array triggerents = triggers.GetChildren(); List <Trigger_Door> doors = new List <Trigger_Door>(); foreach (Area ent in triggerents) { Godot.Collections.Dictionary fields = ent.Get("properties") as Godot.Collections.Dictionary; foreach (DictionaryEntry kvp in fields) { if (kvp.Key.ToString().ToLower() == "classname") { if (kvp.Value.ToString().ToLower() == "trigger_door") { // https://github.com/godotengine/godot/issues/31994#issuecomment-570073343 ulong objId = Convert.ToUInt64(ent.GetInstanceId()); ent.SetScript(ResourceLoader.Load("Scripts/Trigger_Door.cs")); Trigger_Door newEnt = GD.InstanceFromId(objId) as Trigger_Door; newEnt.SetProcess(true); newEnt.Notification(NotificationReady); newEnt.Init(fields); doors.Add(newEnt); } } } } this.LinkDoors(doors); }
// Called when the node enters the scene tree for the first time. public override void _Ready() { target = GetNode <Spatial>(GetTree().Root.GetNode("Spatial/Player").GetPath()); //I should definitely think of a way to make this modular without sacrificing the ability to easily target the player. }
public Ai(Actor actor, Spatial eyes) : base(actor, eyes) { host = actor; target = null; }
public SizeHandler(PlayerController controller, Spatial head) : base(controller, true) { headPos = head; crouched = false; controller.playMovement.RegisterVerticalChange(HardLanding); }
//provides grid based movement and handles collision information public KinematicCollision Move(Vector3 relVec) { if (!_collisionLoaded) { return(null); } relVec *= SPEED; KinematicCollision collision = MoveAndCollide(relVec, testOnly: true); //don't move if it would cause a collision and return that collision if (collision != null) { //handle the collision Node collider = (Node)collision.Collider; string name = NameGetter.FromCollision(collider); switch (name) { case "bambooPlatformStatic": Spatial staticBody = (StaticBody)collider; if (staticBody.Translation.y != 0) { staticBody.Translation = Vector3.Zero; relVec += new Vector3(0, SPEED, 0); collision = null; } break; case "pot": moveWrapper colliderMove = (moveWrapper)collider; if (colliderMove.Move(relVec / SPEED) == null) { collision = null; } break; case "GridMap": case "flowerPlatform": break; default: GD.Print("Unhandled collision against " + name); break; } } //move if it wouldn't cause a collision if (collision == null) { Translation += relVec; if (planted) { var plant = (Spatial)plantRaycast.GetCollider(); if (plant != null) { plant.Translation += relVec; } else { planted = false; } } } return(collision); }
public override bool HasGizmo(Spatial spatial) { return(spatial is UMAOverlay); }
public override void _Ready() { GD.Print("Ready to create world!"); if (densityGeneratorPath == null) { GD.PushError("VoxelTerrain must have a Density Generator."); return; } densityGenerator = GetNode <DensityGenerator>(densityGeneratorPath); if (densityGenerator == null) { GD.PushError("VoxelTerrain could not locate the supplied Density Generator."); return; } if (observerPath == null) { GD.PushError("VoxelTerrain must have an observer."); return; } observer = GetNode <Spatial>(observerPath); if (observer == null) { GD.PushError("VoxelTerrain could not locate the supplied observer."); return; } if (!(observer is Camera)) { observer = (Camera)observer.FindNode("Camera"); } if (debugLabelPath != null) { debugLabel = GetNode <Label>(debugLabelPath); } for (int y = -5; y < 5; y++) { for (int z = -5; z <= 5; z++) { for (int x = -5; x <= 5; x++) { var at = new ChunkPosition(x, y, z); var chunk = new Chunk(at); AddChunk(chunk); var instance = new ChunkInstance(chunk) { MaterialOverride = material }; chunk.InitDensity(densityGenerator.GetDensity); AddChild(instance); } } } var origoChunk = chunks[new ChunkPosition(0, 0, 0)]; origoChunk.GetLuminance().Init(); origoChunk.ForEachChunk(chunk => chunk.TriangulateChunk()); SetPhysicsProcess(true); }
/// <summary> /// Draws the tangent basis (Normal, Tangent, Binormal) of the provided spatial. If the /// spatial is a Node, the child meshes of the spatial will have their /// tangent basis drawn, if the mesh is visible. /// </summary> /// <param name="scene">Scene to draw the tangent basis of.</param> /// <param name="renderer">The renderer</param> public static void DrawTangentBasis(Spatial scene, IRenderer renderer) { DrawTangentBasis(scene, renderer, true); }
public static void SetGlobalPosition(this Spatial spatial, Vector3 position) { spatial.GlobalTransform = new Transform(spatial.GlobalTransform.basis, position); }
/// <summary> /// Draws the spatial's bounding volumes, if visible to /// the renderer's currently active camera. If the spatial is /// a Node, the children of the spatial will be rendered if visible. /// </summary> /// <param name="scene">Scene to draw the bounds of.</param> /// <param name="renderer">The renderer</param> public static void DrawBounds(Spatial scene, IRenderer renderer) { DrawBounds(scene, renderer, true); }
public override void _Ready() { acid = GetChild <Spatial>(1); }
public ActorInputHandler(Actor actor, Spatial eyes) : base(actor, eyes) { InitHeld(); InitEyes(eyes); device = new DeviceManager(DeviceManager.Devices.MouseAndKeyboard, this.eyes as Eyes); }
public void shoot(float delta, bool isPuppet) { if (reloadWeapon) { return; } if (!isPuppet) { return; } // Get bullet ray. RayCast bulletRay = (RayCast)camera.GetNode("bullet_ray"); if (bullets > 0) { bullets -= 1; // Notify bullet update GameState.instance.EmitSignal(nameof(GameState.updateWeapon), weaponName, bullets, ammo); if (camera != null) { // Recoil camera.Rotation = new Vector3( Mathf.Lerp(camera.Rotation.x, (float)GD.RandRange(1, 2), delta), Mathf.Lerp(camera.Rotation.y, (float)GD.RandRange(-1, 1), delta), camera.Rotation.z ); // Shake camera.Set("shakeForce", 0.002); camera.Set("shakeTime", 0.2); } // Audio AudioStreamPlayer3D shoot = ((AudioStreamPlayer3D)audioNode.GetNode("shoot")); shoot.PitchScale = (float)GD.RandRange(0.9, 1.1); shoot.Play(); // Update crosshair crosshair.RectScale = crosshair.RectScale.LinearInterpolate(new Vector2(4, 4), 10 * delta); if (bulletRay.IsColliding()) { // Object collision CollisionObject collisionObject = (CollisionObject)bulletRay.GetCollider(); // Add spark to props. if (collisionObject.IsInGroup("props")) { // Add Spark Particles spark = (Particles)sparkScene.Instance(); ((Node)bulletRay.GetCollider()).AddChild(spark); spark.GlobalTransform = new Transform(spark.GlobalTransform.basis, bulletRay.GetCollisionPoint()); spark.Emitting = true; } // Add Muzzle Particles muzzle = (Particles)muzzleScene.Instance(); barrelNode.AddChild(muzzle); muzzle.Emitting = true; if (collisionObject is KinematicBody) { // Add Blood splatter Particles splatter = (Particles)splatterScene.Instance(); ((Node)bulletRay.GetCollider()).AddChild(splatter); splatter.GlobalTransform = new Transform(splatter.GlobalTransform.basis, bulletRay.GetCollisionPoint()); splatter.Emitting = true; int localDamage = 0; if (collisionObject.IsInGroup("head")) { localDamage = (int)GD.RandRange(damage / 2, damage); } else { localDamage = (int)GD.RandRange(damage / 3, damage / 2); } int colliderId = Convert.ToInt32(collisionObject.Name); // Send damage report. GameState.instance.EmitSignal(nameof(GameState.takeDamage), colliderId, localDamage); return; } else if (collisionObject.IsInGroup("props") || collisionObject.IsInGroup("walls")) { // Apply force to rigid body other than hitbox if (bulletRay.GetCollider() is RigidBody) { int localDamage = (int)GD.RandRange(damage / 1.5f, damage); ((RigidBody)bulletRay.GetCollider()).ApplyCentralImpulse(-bulletRay.GetCollisionNormal() * (localDamage * 0.3f)); } // Apply decal Spatial decal = (Spatial)decalScene.Instance(); ((Node)bulletRay.GetCollider()).AddChild(decal); decal.GlobalTransform = new Transform( decal.GlobalTransform.basis, bulletRay.GetCollisionPoint() ); decal.LookAt(bulletRay.GetCollisionPoint() + bulletRay.GetCollisionNormal(), new Vector3(1, 1, 0)); return; } } } else { AudioStreamPlayer3D empty = ((AudioStreamPlayer3D)audioNode.GetNode("empty")); if (!empty.Playing) { empty.PitchScale = (float)GD.RandRange(0.9, 1.1); empty.Play(); } } }
/// <summary> /// Gets an IEnumerable of the GrhIndexes used in the map. /// </summary> /// <returns>An IEnumerable of the GrhIndexes used in the map.</returns> IEnumerable <GrhIndex> GetMapGrhList() { return(Spatial.GetMany <MapGrh>().Select(x => x.Grh.GrhData.GrhIndex).OrderBy(x => x).Distinct().ToImmutable()); }
public override void _Ready() { PlanetSelectionIndicator = GD.Load <PackedScene>("res://Prefabs/UI/PlanetSelection.tscn"); cam = GetViewport().GetCamera(); cam.AddChild(planetSpawner); }
public void Draw(ISpriteBatch sb) { var cam = Camera; if (cam == null) { const string errmsg = "The camera on map `{0}` was null - cannot draw map."; if (log.IsErrorEnabled) { log.ErrorFormat(errmsg, this); } Debug.Fail(string.Format(errmsg, this)); return; } // Find the drawable objects that are in view and pass the filter (if one is provided) var viewArea = cam.GetViewArea(); IEnumerable <IDrawable> drawableInView; IEnumerable <IDrawable> bgInView; if (DrawFilter != null) { drawableInView = Spatial.GetMany <IDrawable>(viewArea, x => DrawFilter(x)); bgInView = _backgroundImages.Cast <IDrawable>().Where(x => DrawFilter(x) && x.InView(cam)); } else { drawableInView = Spatial.GetMany <IDrawable>(viewArea); bgInView = _backgroundImages.Cast <IDrawable>().Where(x => x.InView(cam)); } // Concat the background images (to the start of the list) since they aren't in any spatials drawableInView = bgInView.Concat(drawableInView); if (BeginDrawMap != null) { BeginDrawMap.Raise(this, new DrawableMapDrawEventArgs(sb, cam)); } // Sort all the items, then start drawing them layer-by-layer, item-by-item foreach (var layer in _drawableSorter.GetSorted(drawableInView)) { var layerEventArgs = new DrawableMapDrawLayerEventArgs(layer.Key, sb, cam); // Notify the layer has started drawing if (BeginDrawMapLayer != null) { BeginDrawMapLayer.Raise(this, layerEventArgs); } // Draw the normal map objects foreach (var drawable in layer.Value) { drawable.Draw(sb); } // Get the effects to draw, then draw them (if possible) IEnumerable <ITemporaryMapEffect> tempMapEffects; switch (layer.Key) { case MapRenderLayer.SpriteBackground: tempMapEffects = _mapEffects.Where(x => !x.IsForeground); break; case MapRenderLayer.SpriteForeground: tempMapEffects = _mapEffects.Where(x => x.IsForeground); break; default: tempMapEffects = null; break; } if (tempMapEffects != null) { foreach (var mapEffect in tempMapEffects) { mapEffect.Draw(sb); } } // Notify the layer has finished drawing if (EndDrawMapLayer != null) { EndDrawMapLayer.Raise(this, layerEventArgs); } } // Draw the particle effects if (DrawParticles) { foreach (var pe in ParticleEffects) { pe.Draw(sb); } } if (EndDrawMap != null) { EndDrawMap.Raise(this, new DrawableMapDrawEventArgs(sb, cam)); } }
private void SpatialInitialization() { spatial = new Spatial(); spatial.Attach += new AttachEventHandler(delegate(object sender, AttachEventArgs e){ Console.WriteLine("Spatial {0} attached!", e.Device.SerialNumber.ToString()); }); spatial.Detach += new DetachEventHandler(delegate(object sender, DetachEventArgs e){ Console.WriteLine("Spatial {0} detached!", e.Device.SerialNumber.ToString()); }); spatial.Error += new Phidgets.Events.ErrorEventHandler(delegate(object sender, Phidgets.Events.ErrorEventArgs e){ Console.Write(e.Description); }); spatial.SpatialData += new SpatialDataEventHandler(SpatialData); spatial.open(); Console.WriteLine("Waiting for spatial to be attached...."); spatial.waitForAttachment(); spatial.DataRate = 80 ; }
public static IObservable <bool> OnVisibilityChange(this Spatial node) { return(node.FromSignal("visibility_changed").Select(_ => node.Visible)); }