public float Raycast(Spatial scene, Vector3 from, Vector3 to, Array excl = null) { PhysicsDirectSpaceState spaceState = scene.GetWorld().DirectSpaceState; Dictionary result; if (excl != null) { result = spaceState.IntersectRay(from, to, excl); } else { result = spaceState.IntersectRay(from, to); } if (result.Count > 0) { return(((Vector3)result["position"]).y); } return(0); /* * { * position: Vector3 # point in world space for collision * normal: Vector3 # normal in world space for collision * collider: Object # Object collided or null (if unassociated) * collider_id: ObjectID # Object it collided against * rid: RID # RID it collided against * shape: int # shape index of collider * metadata: Variant() # metadata of collider * } */ }
public override void _PhysicsProcess(float delta) { if (do_raycast == true) { do_raycast = false; PhysicsDirectSpaceState spaceState = GetWorld().DirectSpaceState; Godot.Collections.Dictionary results = spaceState.IntersectRay(ray_origin, ray_end, null, 512u); if (results.Count > 0) { if (results["collider"] is Spatial spatial) { if (spatial.GetParent() is Tabs tabs) { currentHighlighted = tabs; tabs.MouseEnter(true); ResetPageFlip(); return; } if (spatial.GetParent() is FlipPages flip) { flipPages = flip; flipPages.Hovering(true); return; } } } if (currentHighlighted != null) { currentHighlighted.MouseEnter(false); currentHighlighted = null; } ResetPageFlip(); } }
public override void GridUpdate() { HashSet <PipeCoreLogic> OriginalFriends = Friends; Friends = new HashSet <PipeCoreLogic>(); PhysicsDirectSpaceState State = GetWorld().DirectSpaceState; Godot.Collections.Dictionary Results; Results = State.IntersectRay(Translation, Position1.GlobalTransform.origin, new Godot.Collections.Array() { this, OpenEnd, Game.PossessedPlayer }, 2 | 4); if (Results.Count > 0 && Results["collider"] is OpenEnd) { OpenEndMesh.Show(); OpenEndCollision.Disabled = false; System.Consume(((OpenEnd)Results["collider"]).Parent.System); Friends.Add(((OpenEnd)Results["collider"]).Parent); } else { OpenEndMesh.Hide(); OpenEndCollision.Disabled = true; } if (InitiallyFilledFriends && !Friends.SetEquals(OriginalFriends)) { System = new PipeSystem(this); RecursiveAddFriendsToSystem(); } InitiallyFilledFriends = true; }
public PhysicsBody ShouldEatState() { float minDistanceSquared = 1000.0f * 1000.0f; PhysicsBody minTarget = null; bool found = false; foreach (PhysicsBody b in foodInRange) { if (b == null || !b.IsInGroup("alive")) { continue; } // Identify whether we can see the target by raycasting PhysicsDirectSpaceState spaceState = component.Body.GetWorld().GetDirectSpaceState(); var result = spaceState.IntersectRay(component.Body.GetTranslation(), b.GetTranslation(), new[] { component.Body, b }); if (result.Count == 0) { found = true; float distanceSquared = component.Body.GetTranslation().DistanceSquaredTo(b.GetTranslation()); if (distanceSquared < minDistanceSquared) { minDistanceSquared = distanceSquared; minTarget = b; } } } if (found) { return(minTarget); } return(null); }
/*public override void _Input(InputEvent @event) * { * if(@event is InputEventMouseMotion evento) * { * * } * }*/ private void RayoDeCamara() //funcion para tirar un rayo desde la camara y determinar la posición del mouse con respecto a la camara { if (CamaraActiva == "Camera_aguila") { camaraActual = Camera_aguila; GD.Print("estoy en Camera_aguila"); } if (CamaraActiva == "Camera_superior") { camaraActual = Camera_superior; GD.Print("estoy en Camera_superior"); } if (CamaraActiva == "Camera_vista_media") { camaraActual = Camera_vista_media; GD.Print("estoy en Camera_vista_media"); } origen = camaraActual.ProjectRayOrigin(GetGlobalMousePosition()); //determina la posición de la camara 3D respecto al viewport destino = origen + camaraActual.ProjectRayNormal(GetLocalMousePosition()) * RayoDistancia; //rayo lanzado desde la camara y el mouse espacio = camaraActual.GetWorld().DirectSpaceState; intercepto = espacio.IntersectRay(origen, destino, new Godot.Collections.Array { }, 1); //esto es una variable global para saber la posición del mouse if (intercepto.Contains("position")) //si el diccionario tiene esa clave { edificioInstanciado.Translation = (Vector3)intercepto["position"]; //guardo la posición del mouse GD.Print(intercepto["position"]); //imprimo por pantalla la ubicación del mouse } }
public override void _Ready() { cameraPivot = GetNode <Spatial>(CameraPivot); camera = GetNode <Camera>(CameraPath); camera.LookAt(Translation, Vector3.Up); spaceState = GetWorld().DirectSpaceState; }
public override void _Ready() { sprite = GetNode <Sprite3D>("Sprite"); movementArea = GetNode <Spatial>("MovementArea"); spaceState = GetWorld().DirectSpaceState; AddToGroup("Units"); }
public static void Interact() { Game.PossessedPlayer.MatchSome( (Plr) => { Vector3 Start = Plr.Translation; Vector3 End = Start + new Vector3(0, 0, Player.InteractReach) .Rotated(new Vector3(1, 0, 0), Deg2Rad(Plr.ActualLookVertical)) .Rotated(new Vector3(0, 1, 0), Deg2Rad(Plr.LookHorizontal)); var Exclude = new Godot.Collections.Array { Plr }; PhysicsDirectSpaceState State = Plr.GetWorld().DirectSpaceState; Godot.Collections.Dictionary Results = State.IntersectRay(Start, End, Exclude, 4); if (Results.Count > 0) { object RawCollider = Results["collider"]; if (RawCollider is Locker CollidedLocker) { Menu.BuildInteractInventory(CollidedLocker); } } } ); }
public void PerformHitscan() { ActualAssert(ParentPlayer != null); Vector3 Origin = ParentPlayer.Cam.GlobalTransform.origin; Vector3 Endpoint = Origin + new Vector3(0, 0, -Range) .Rotated(new Vector3(1, 0, 0), Deg2Rad(ParentPlayer.CamJoint.RotationDegrees.x + ParentPlayer.Cam.RotationDegrees.x)) .Rotated(new Vector3(0, 1, 0), Deg2Rad(ParentPlayer.RotationDegrees.y)); Vector3 BaseEndpoint = Endpoint; int PelletsLeft = CurrentWeapon.PelletCount; while (PelletsLeft > 0) { if (CurrentWeapon.Kind == WeaponKind.SHOTGUN) { const int DeviationDistance = 18; Endpoint = BaseEndpoint + new Vector3( Game.Rng.Next(DeviationDistance) * RandomSign(), Game.Rng.Next(DeviationDistance) * RandomSign(), Game.Rng.Next(DeviationDistance) * RandomSign() ); } var Exclude = new Godot.Collections.Array() { ParentPlayer }; PhysicsDirectSpaceState State = GetWorld().DirectSpaceState; Godot.Collections.Dictionary Results = State.IntersectRay(Origin, Endpoint, Exclude, 1 | 2); if (Results.Count > 0) { var Position = (Vector3)Results["position"]; var Normal = (Vector3)Results["normal"]; if (Results["collider"] is Hitbox Box) { int Damage = CurrentWeapon.BodyDamage; if (Box.Kind == HitboxKind.HEAD) { Damage = CurrentWeapon.HeadDamage; } Box.Damage(Damage); Sfx.PlaySfxSpatially(SfxCatagory.FLESH_HIT, 0, Position, 0); } else { Sfx.PlaySfxSpatially(SfxCatagory.BULLET_HIT, 0, Position, 0); } Particles.Spawn(Particle.PISTOL_IMPACT, Position, Normal); } PelletsLeft -= 1; } }
public void CalcProjectile() { spaceState = Main.instance.GetWorld().DirectSpaceState; var camera = Main.camera; bulletEndPos = bulletStartPos + camera.ProjectRayNormal(Helpers.GetScreenCenter()) * travelDistanceLimit; CalcProjectileStepForward(); }
private void MoveAsRay(float delta) { Transform t = GlobalTransform; Vector3 origin = t.origin; Vector3 forward = -t.basis.z; Vector3 dest = origin; dest += (forward * _def.launchSpeed) * delta; uint mask = uint.MaxValue; PhysicsDirectSpaceState space = GetWorld().DirectSpaceState; Godot.Collections.Array arr = null; if (_ignoreBody != null) { arr = new Godot.Collections.Array(); arr.Add(_ignoreBody); } Dictionary hitResult = space.IntersectRay(origin, dest, arr, mask); if (hitResult.Keys.Count > 0) { _touch.damage = _def.damage; _touch.teamId = 0; _touch.touchType = TouchType.Bullet; IActorProvider actorProvider = hitResult["collider"] as IActorProvider; if (actorProvider != null) { IActor actor = actorProvider.GetActor(); if (actor != null) { TouchResponseData response = actor.ActorTouch(_touch); Console.WriteLine($"Prj hit actor for {response.damageTaken}"); } else { Console.WriteLine($"Prj hit provider but actor is null!"); } } else { //Node hitObj = (hitResult["collider"] as Node); //Console.WriteLine($"Prj hit non-actor node {hitObj.Name}"); } Vector3 gfxOrigin = (Vector3)hitResult["position"]; GFXQuick gfx = Main.i.factory.SpawnGFX(GameFactory.Path_GFXImpact); gfx.Spawn(gfxOrigin); Die(); return; } t.origin = dest; GlobalTransform = t; }
public static Godot.Collections.Dictionary CastRay( Spatial worldSourceNode, Vector3 origin, Vector3 target, uint mask, PhysicsBody ignoreBody) { Godot.Collections.Array ignoreBodies = null; if (ignoreBody != null) { ignoreBodies = new Godot.Collections.Array(); ignoreBodies.Add(ignoreBody); } PhysicsDirectSpaceState space = worldSourceNode.GetWorld().DirectSpaceState; return(space.IntersectRay(origin, target, ignoreBodies, mask, true, true)); }
/// <summary> /// Uses raycasting to determine what collision object is under the mouse pointer /// </summary> private Godot.Collections.Dictionary GetObjUnderMouse() { Viewport viewport = GetNode <Viewport>("/root/main/UI/AppWindow/EnvironmentContainer/4WayViewport/VerticalSplit/HSplit1/Viewport1/Viewport"); // Viewport viewport = GetViewport(); Vector2 mousePos = viewport.GetMousePosition(); Vector3 rayFrom = viewport.GetCamera().ProjectRayOrigin(mousePos); Vector3 rayTo = rayFrom + viewport.GetCamera().ProjectRayNormal(mousePos) * 1000; PhysicsDirectSpaceState spaceState = GetWorld().DirectSpaceState; var selection = spaceState.IntersectRay(rayFrom, rayTo); return(selection); }
public override void _Ready() { player = GetNode(Game.PLAYER_PATH) as Player; // Called every time the node is added to the scene. // Initialization here spaceState = GetWorld().DirectSpaceState; terrain = GetNode(Game.TERRAIN_PATH) as Terrain; plants = GetNode(Game.PLANTS_PATH) as Plants; }
public override void OnBinding(Agent agent) { this.agent = agent; this.spaceState = (agent.GetBody() as KinematicBody).GetWorld().DirectSpaceState; if (this.eyePath != null && this.eyePath != "") { this.eye = GetNode(this.eyePath) as Spatial; } else { this.eye = agent.GetBody() as Spatial; } OnReset(agent); }
public void Explode(Vector3 Position) { foreach (Node Body in AffectedBodies) { if (Body is IPushable Pushable) { PhysicsDirectSpaceState State = GetWorld().DirectSpaceState; Godot.Collections.Dictionary Results = State.IntersectRay(Position, Pushable.Translation, new Godot.Collections.Array() { Pushable }, 1); if (Results.Count > 0) { continue; } float Distance = Clamp(Position.DistanceTo(Pushable.Translation), 1, MaxRocketDistance); float Power = LogBase(-Distance + MaxRocketDistance + 1, 2) / LogBase(MaxRocketDistance + 1, 2); Vector3 Push = ((Pushable.Translation - Position) / MaxRocketDistance).Normalized() * MaxRocketPush * Power; { Vector3 Flat = Push.Flattened(); Flat *= RocketHorizontalMultiplyer; Push.x = Flat.x; Push.z = Flat.z; } Push.y *= RocketVerticalMultiplyer; Pushable.ApplyPush(Push); } } AffectedBodies.Clear(); var ExplodeSfxInstance = (AudioStreamPlayer3D)ExplodeSfx.Instance(); ExplodeSfxInstance.Play(); ExplodeSfxInstance.Translation = Position; World.EntitiesRoot.AddChild(ExplodeSfxInstance); var ParticleSystem = (CPUParticles)ExplodeParticles.Instance(); ParticleSystem.Translation = Position; ParticleSystem.Emitting = true; World.EntitiesRoot.AddChild(ParticleSystem); QueueFree(); }
void OrientReadingTarget() { Vector2 mouse_pos = GetViewport().GetMousePosition(); Vector3 from = camera.ProjectRayOrigin(mouse_pos); Vector3 to = from + camera.ProjectRayNormal(mouse_pos) * RAY_LEN; PhysicsDirectSpaceState space = GetWorld().DirectSpaceState; Dictionary result = space.IntersectRay(from, to, collideWithBodies: false, collideWithAreas: true); if (result.Count > 0) { Vector3 position = (Vector3)result["position"]; flashlight_reading_target.GlobalTransform = flashlight_reading_target.GlobalTransform.LookingAt(position, Vector3.Up); } }
public override void _PhysicsProcess(float Delta) { PhysicsDirectSpaceState State = GetWorld().DirectSpaceState; Godot.Collections.Dictionary Results = State.IntersectRay(StartPoint.GetGlobalTransform().origin, EndPoint.GetGlobalTransform().origin, new Godot.Collections.Array() { Game.PossessedPlayer }, 2); if (Results.Count > 0) { (Parent as IProjectileCollision).ProjectileCollided((Vector3)Results["position"]); } }
public override void _PhysicsProcess(float delta) { if (!GameManager.Instance.playing) { return; } if (scanPulseCharge < 10) { scanPulseCharge++; } else { scanPulseCharge = 0; ray_origin = camera.ProjectRayOrigin(GetViewport().Size / 2); ray_end = ray_origin + camera.ProjectRayNormal(GetViewport().Size / 2) * rayLength; do_raycast = true; } if (do_raycast) { do_raycast = false; PhysicsDirectSpaceState spaceState = GetWorld().DirectSpaceState; Godot.Collections.Dictionary results = spaceState.IntersectRay(ray_origin, ray_end, null, 256u); if (results.Count > 0) { if (results["collider"] is Spatial spatial) { if (spatial.GetParent() is Scannables scan) { if (current != scan) { if (!scan.WasScanned()) { current = scan; EmitSignal("FoundScannable", current); return; } } return; } } } if (current != null) { current = null; EmitSignal("LostScannables"); } } }
protected void FindRadius(Player ignore, float damage) { // test for radius damage SphereShape s = new SphereShape(); s.SetRadius(_areaOfEffectRadius); // Get space and state of the subject body RID space = PhysicsServer.BodyGetSpace(this.GetRid()); PhysicsDirectSpaceState state = PhysicsServer.SpaceGetDirectState(space); // Setup shape query parameters PhysicsShapeQueryParameters par = new PhysicsShapeQueryParameters(); par.SetShapeRid(s.GetRid()); par.Transform = this.Transform; Godot.Collections.Array result = state.IntersectShape(par); foreach (Dictionary <object, object> r in result) { if (r["collider"] is Player pl) { GD.Print("found player"); if (pl != ignore || ignore == null) { // find how far from explosion as a percentage, apply to damage float dist = this.Transform.origin.DistanceTo(pl.Transform.origin); dist = dist > this._areaOfEffectRadius ? (this._areaOfEffectRadius * .99f) : dist; float pc = ((this._areaOfEffectRadius - dist) / this._areaOfEffectRadius); float d = damage * pc; GD.Print("dam: " + damage); GD.Print("pc: " + pc); GD.Print("dist: " + dist); GD.Print("aoe: " + this._areaOfEffectRadius); GD.Print(this._playerOwner.GetName()); GD.Print(pl.GetName()); if (pl == this._playerOwner) { d = d * 0.5f; } GD.Print("inflicted dam: " + d); // inflict damage pl.TakeDamage(this.Transform, _weaponOwnerString, _weaponOwnerInflictLength, this._playerOwner, d); } } } }
private Node GetObjectUnderMouse() { Vector2 mousePos = (Vector2) new Vector2(0, 0); mousePos = GetViewport().GetMousePosition(); Vector3 rayFrom = ToGlobal(((Camera)GetNode("../CameraHolder/Camera")).ProjectRayOrigin(mousePos)); Vector3 rayTo = rayFrom + ToGlobal(((Camera)GetNode("../CameraHolder/Camera")).ProjectRayNormal(mousePos)) * 10000; PhysicsDirectSpaceState spaceState = GetWorld().DirectSpaceState; var hit = spaceState.IntersectRay(rayFrom, rayTo); Node selection = (Node) new Node(); if (hit.Contains("collider")) { selection = (Node)hit["collider"]; } return(selection); }
public override void _PhysicsProcess(float Delta) { PhysicsDirectSpaceState State = GetWorld().DirectSpaceState; Godot.Collections.Dictionary Results = State.IntersectRay( StartPoint.GlobalTransform.origin, EndPoint.GlobalTransform.origin, new Godot.Collections.Array { Net.Players[Parent.FirerId].Plr.ValueOr(() => null) }, 1 ); if (Results.Count > 0) { Parent.ProjectileCollided((Vector3)Results["position"]); } }
public void UpdateFloor() { PhysicsDirectSpaceState State = GetWorld().DirectSpaceState; var Excluding = new Godot.Collections.Array { this }; Vector3 End = Translation + Bottom + new Vector3(0, -2, 0); var Results = State.IntersectRay(Translation, End, Excluding, 3); if (Results.Count > 0) { if (Results["collider"] is Tile Branch && Branch.Point != null) { Floor = Branch.Some(); } } }
public override void _PhysicsProcess(float delta) { //So we need to check if the player is in cover //We do this by casting a ray up and in the direction of the wind Vector3 checkDir = 10 * new Vector3( -direction.x, 2, -direction.y ).Normalized(); PhysicsDirectSpaceState spaceState = GetWorld() .GetDirectSpaceState(); Vector3 zeroVec = new Vector3(0, 0, 0); Dictionary <object, object> collisions = spaceState.IntersectRay( player.ToGlobal(zeroVec), player.ToGlobal(checkDir), new Godot.Object[] { player } ); if (collisions.Count == 0) { //So we're going to push. //to create a feling of being "hurled" we'll sin2 the current time. float playerYpos = player.ToGlobal(zeroVec).y; float upThrust = 0; //50 is the highest the storm will carry the player upward if (playerYpos < 50) { upThrust = (float)(1 - Math.Cos(timeAlive / LIFE_TIME * 5.0 * Math.PI)); } Vector3 pushAmount = new Vector3( direction.x, upThrust, direction.y ).Normalized(); player.Push(pushAmount); } }
public static object RayCast(Vector3 start, Vector3 end, World world) { if (world == null) { return(null); } PhysicsDirectSpaceState spaceState = world.DirectSpaceState as PhysicsDirectSpaceState; var result = spaceState.IntersectRay(start, end); if (!result.ContainsKey("collider")) { return(null); } object collider = result["collider"]; return(collider); }
Actor RayCastForActor(Vector3 start, Vector3 end) { PhysicsDirectSpaceState spaceState = host.GetWorld().DirectSpaceState as PhysicsDirectSpaceState; var result = spaceState.IntersectRay(start, end); if (!result.ContainsKey("collider")) { return(null); } object collider = result["collider"]; Actor candidate = collider as Actor; if (candidate != host) { return(candidate); } return(null); }
// FIXME - increase max number of results // this has a max number of results that get filled with static bodies... public Godot.Collections.Array FindRadius(KinematicBody body, float radius) { // test for radius SphereShape s = new SphereShape(); s.Radius = radius; // Get space and state of the subject body RID space = PhysicsServer.BodyGetSpace(body.GetRid()); PhysicsDirectSpaceState state = PhysicsServer.SpaceGetDirectState(space); // Setup shape query parameters PhysicsShapeQueryParameters par = new PhysicsShapeQueryParameters(); par.ShapeRid = s.GetRid(); par.Transform = body.Transform; return(state.IntersectShape(par, 100)); }
private Tuple <Vector3, PuffType, Node, KinematicBody, float> DoHit(PhysicsDirectSpaceState spaceState, Vector3 shootOrigin, Vector3 shootTo, Player shooter) { Tuple <Vector3, PuffType, Node, KinematicBody, float> hitData = null; Godot.Collections.Dictionary res = spaceState.IntersectRay(shootOrigin, shootTo, new Godot.Collections.Array { this, shooter }, 1); if (res.Count > 0) { Vector3 pos = (Vector3)res["position"]; PuffType puff; Node colNode = null; KinematicBody hit = null; float dam = 0; // track if collides, track puff counts // leave this for fun if (res["collider"] is RigidBody rb) { Vector3 impulse = (pos - shooter.GlobalTransform.origin).Normalized(); Vector3 position = pos - rb.GlobalTransform.origin; rb.ApplyImpulse(position, impulse * 10); puff = PuffType.Puff; colNode = (Node)rb; } else if (res["collider"] is KinematicBody kb) { hit = kb; dam = _damage / _pelletCount; puff = PuffType.Blood; colNode = (Node)kb; } else { puff = PuffType.Puff; } hitData = new Tuple <Vector3, PuffType, Node, KinematicBody, float>(pos, puff, colNode, hit, dam); } return(hitData); }
public override void _PhysicsProcess(float delta) { Transform t = _originNode.GlobalTransform; Vector3 origin = t.origin; Vector3 forward = -t.basis.z; Vector3 dest = origin + (forward * _length); Vector3 finalPos = dest; uint mask = uint.MaxValue; PhysicsDirectSpaceState space = GetWorld().DirectSpaceState; Dictionary hitResult = space.IntersectRay(origin, dest, null, mask); if (hitResult.Keys.Count > 0) { finalPos = (Vector3)hitResult["position"]; } Transform selfT = GlobalTransform; selfT.origin = finalPos; GlobalTransform = selfT; }
protected Godot.Collections.Array FindPlayersInRadius() { SphereShape s = new SphereShape(); s.SetRadius(_areaOfEffectRadius); // Get space and state of the subject body RID space = PhysicsServer.BodyGetSpace(this.GetRid()); PhysicsDirectSpaceState state = PhysicsServer.SpaceGetDirectState(space); // Setup shape query parameters PhysicsShapeQueryParameters par = new PhysicsShapeQueryParameters(); par.SetShapeRid(s.GetRid()); par.Transform = this.Transform; Godot.Collections.Array result = state.IntersectShape(par); return(result); }