コード例 #1
0
ファイル: Person.cs プロジェクト: CastleOfArgg/Blues
    public void Fire()
    {
        Weapon.Attack();
        if (Weapon.ProjectileType != Projectile.Type.None)
        {
            //put projectile in game
            var scene2         = (PackedScene)GD.Load(Resources.ScenePath + Weapon.ProjectileType.ToString() + ".tscn");
            var sceneInstance2 = (Projectile)scene2.Instance();
            var scale          = sceneInstance2.Scale;
            Globals.Instance.CurrentLevel.GetNode("Projectiles").AddChild(sceneInstance2);
            var offset = Globals.GetRotationFrom(Resources.ProjectileOffset, BulletRay.GlobalTransform.basis.GetEuler());
            sceneInstance2.Transform = new Transform(BulletRay.GlobalTransform.basis, BulletRay.GlobalTransform.origin + offset);

            //
            Vector3 forceSource = BulletRay.GlobalTransform.basis.GetEuler();
            var     bowPosition = new Vector3(sceneInstance2.GlobalTransform.origin)
            {
                y = 0
            };
            var hitPosition = Globals.GetRotationFrom(BulletRay.CastTo, BulletRay.GlobalTransform.basis.GetEuler());
            if (BulletRay.IsColliding())
            {
                hitPosition = new Vector3(BulletRay.GetCollisionPoint())
                {
                    y = 0
                }
            }
            ;
            forceSource.y = Mathf.Atan2(-(bowPosition.x - hitPosition.x), -(bowPosition.z - hitPosition.z));

            //apply force to projectile
            var force = Globals.GetRotationFrom(Resources.ProjectileImpulse, forceSource);
            sceneInstance2.ApplyCentralImpulse(force);
            sceneInstance2.Scale  = scale * 10;
            sceneInstance2.Damage = Weapon.Damage;
            sceneInstance2.Firer  = this;
            GD.Print(BulletRay.GetCollisionPoint().DistanceTo(GlobalTransform.origin));
            if (BulletRay.GetCollisionPoint().DistanceTo(GlobalTransform.origin) <= Resources.TooCloseDistance)
            {
                sceneInstance2.IsTooClose = true;
            }
            return;
        }

        var other = (Spatial)BulletRay.GetCollider();

        if (other == null)
        {
            return;
        }

        if (other.GetParent().GetParent().GetParent() is Person person)
        {
            person.TakeDamage(Weapon.Damage);
        }
        //TODO Add other colliders

        var pos = BulletRay.GetCollisionPoint();
        //TODO blood or something (Particals)
    }
コード例 #2
0
    public Vector3 GetTeleportLocation()
    {
        // get weighted sum of all
        Vector3 resultant     = Vector3.Zero;
        Spatial detector      = GetNode <Spatial>("Detectors");
        RayCast bottomRaycast = detector.GetNode <RayCast>("bottom");

        bottomRaycast.ForceRaycastUpdate();
        if (!bottomRaycast.IsColliding())
        {
            Util.DrawSphere(bottomRaycast.GetCollisionPoint(), detector);
        }

        foreach (RayCast cast in _detectorList)
        {
            cast.ForceRaycastUpdate();
            if (cast.IsColliding())
            {
                // get collision point in local coordinates to detector spatial in middle of sword
                Vector3 collisionVector = cast.Transform.XformInv(cast.GetCollisionPoint());
                resultant += cast.GetCollisionNormal() * (1 - Mathf.Min(collisionVector.Length(), _minDetectorWeight));
            }
        }

        // return average of normals
        return(Transform.origin + resultant.Normalized());
    }
コード例 #3
0
    //Called whenever the player inputs something
    public override void _Input(InputEvent @event)
    {
        if (@event is InputEventMouseMotion event_mouse_motion)
        {
            //Move camera according to mouse motion
            head.RotateY(Deg2Rad(-1 * event_mouse_motion.Relative.x * mouse_sens));
            float dx_rot = event_mouse_motion.Relative.y * mouse_sens;
            if (cam_angle - dx_rot > -90 && cam_angle - dx_rot < 90)
            {
                cam.RotateX(Deg2Rad(-1 * dx_rot));
                cam_angle -= dx_rot;
            }
        }

        if (@event.IsActionPressed("player_block_place") && raycast.IsColliding() && mat != null)
        {
            //Place blocks!
            int[] g_pos = Vector3ToInts(world_grid.WorldToMap(raycast.GetCollisionPoint() + TOLERANCE * Heading()));
            if (world_grid.GetCellItem(g_pos[0], g_pos[1], g_pos[2]) == -1)
            {
                world_grid.SetCellItem(g_pos[0], g_pos[1], g_pos[2], mat.ml_idx);
            }
        }

        if (@event.IsActionReleased("player_pause"))
        {
            cap_mouse = !cap_mouse;
            SwitchMouseMode();
        }
    }
コード例 #4
0
 public override void _Ready()
 {
     wall    = GD.Load <PackedScene>("res://Scenes/DeployableWall.tscn");
     player  = (Player)GetParent().Owner;
     raycast = (RayCast)GetParent();
     SetAsToplevel(true);
     Translation = raycast.GetCollisionPoint();
 }
コード例 #5
0
    public void dispara()
    {
        try {
            Jugador jugador = (Jugador)GetNode("Jugador");

            // efecto del disparo
            jugador.disparaArma();

            Spatial Cabeza    = (Spatial)jugador.GetNode("Cabeza");
            Camera  objcamera = (Camera)Cabeza.GetNode("Camera");
            RayCast ray       = (RayCast)objcamera.GetNode("RayCast");

            if (ray.Enabled && ray.IsColliding())
            {
                Godot.Object objetivo = (Godot.Object)ray.GetCollider();

                Vector3 vectorimpacto = ray.GetCollisionPoint();

                // si el impacto lo recibe un objeto preparado para recibir balas
                if (objetivo.HasMethod("recibeBala"))
                {
                    // calculamos la direccion del impacto
                    Vector3 inicio    = ray.Translation;
                    Vector3 vectordir = vectorimpacto - inicio;

                    objetivo.Call("recibeBala", vectordir);
                }

                // pintamos el impacto de la bala

                // debug con cajas en vez de impacto

                poneCajaEscenario(vectorimpacto);

                /*
                 * PackedScene objeto = (PackedScene)ResourceLoader.Load("res://objetos/mini/ImpactoBalaPared.tscn");
                 * //  objetos.mini.ImpactoBalaPared efecto = (objetos.mini.ImpactoBalaPared)objeto.Instance();
                 * ImpactoBalaPared efecto = (ImpactoBalaPared)objeto.Instance();
                 * AddChild(efecto);
                 * efecto.haceEfecto(vectorimpacto);
                 */
            }
        }
        catch (Exception ex) {
        }
    }
コード例 #6
0
        private void FireBullet()
        {
            if (UseRaycast)
            {
                _nodeRayCast.LookAt(_currentTarget.GlobalTransform.origin
                                    + new Vector3(0, PlayerHeight, 0), new Vector3(0, 1, 0));
                _nodeRayCast.ForceRaycastUpdate();
                if (_nodeRayCast.IsColliding())
                {
                    var body = _nodeRayCast.GetCollider();
                    if (body.HasMethod("BulletHit"))
                    {
                        body.Call("BulletHit", TurretDamageRaycast, _nodeRayCast.GetCollisionPoint());
                    }
                }
            }
            else
            {
                var clone     = _bulletScene.Instance <Bullet>();
                var sceneRoot = GetTree().Root.GetChildren()[0] as Node;
                if (sceneRoot == null)
                {
                    return;
                }
                sceneRoot.AddChild(clone);
                clone.GlobalTransform = GetNode <Spatial>("Head/Barrel_End").GlobalTransform;
                clone.Scale           = new Vector3(8, 8, 8);
                clone.BulletDamage    = TurretDamageBullet;
                clone.BulletSpeed     = 60;
            }

            GetNode <Globals>("/root/Globals").PlaySound("Pistol_shot", false, GlobalTransform.origin);
            _ammoInTurret -= 1;

            _nodeFlashOne.Visible = true;
            _nodeFlashTwo.Visible = true;

            _flashTimer = FlashTime;
            _fireTimer  = FireTime;

            if (_ammoInTurret <= 0)
            {
                _ammoReloadTimer = AmmoReloadTime;
            }
        }
コード例 #7
0
ファイル: Turret.cs プロジェクト: LeonWilzer/Godot-Test-FPS
    public void FireBullet()
    {
        if (_useRaycast)
        {
            _nodeRaycast.LookAt(_currentKinematic.GlobalTransform.origin + new Vector3(0, _playerHeight, 0), new Vector3(0, 1, 0));

            _nodeRaycast.ForceRaycastUpdate();

            if (_nodeRaycast.IsColliding())
            {
                Godot.Object _body = _nodeRaycast.GetCollider();
                if (_body.HasMethod("BulletHit"))
                {
                    _callback = GD.FuncRef(_body, "BulletHit");
                    _callback.CallFunc(_TurretDamageRaycast, _nodeRaycast.GetCollisionPoint());
                }
                _ammoInTurret--;
            }
        }
        else
        {
            StandardBullet _clone     = (StandardBullet)_bulletScene.Instance();
            Node           _sceneRoot = GetTree().Root.GetChild(0);
            _sceneRoot.AddChild(_clone);

            _clone.GlobalTransform = GetNode <Spatial>("Head/Barrel_End").GlobalTransform;
            _clone.Scale           = new Vector3(10, 10, 5);
            _clone.BulletDamage    = _TurretDamageBullet;
            _clone.BulletSpeed     = 5;
            _clone.Gravity         = -0.1f;

            _ammoInTurret--;
        }

        _nodeFlashOne.Visible = true;
        _nodeFlashTwo.Visible = true;

        _flashTimer = _flashTime;
        _fireTimer  = _fireTime;

        if (_ammoInTurret <= 0)
        {
            _ammoReloadTimer = _ammoReloadTime;
        }
    }
コード例 #8
0
    private void FireBullet()
    {
        if (UseRaycast == true)
        {
            _nodeRaycast.LookAt(_currentTarget.GlobalTransform.origin + new Vector3(0, PLAYER_HEIGHT, 0), Vector3.Up);
            _nodeRaycast.ForceRaycastUpdate();

            if (_nodeRaycast.IsColliding())
            {
                var body = _nodeRaycast.GetCollider();
                if (body.HasMethod("BulletHit"))
                {
                    (body as Player).BulletHit(TURRET_DAMAGE_RAYCAST, _nodeRaycast.GetCollisionPoint());
                }

                _ammoInTurret -= 1;
            }
        }
        else
        {
            var clone     = _bulletScene.Instance() as BulletScript;
            var sceneRoot = GetTree().Root.GetChildren()[0] as Spatial;
            sceneRoot.AddChild(clone);

            clone.GlobalTransform = GetNode <Spatial>("Head/Barrel_End").GlobalTransform;
            clone.Scale           = new Vector3(8, 8, 8);
            clone.BULLET_DAMAGE   = TURRET_DAMAGE_BULLET;
            clone.BULLET_SPEED    = 60;

            _ammoInTurret -= 1;
        }

        _nodeFlashOne.Visible = true;
        _nodeFlashTwo.Visible = true;

        _flashTimer = FLASH_TIME;
        _fireTimer  = FIRE_TIME;

        if (_ammoInTurret <= 0)
        {
            _ammoReloadTimer = AMMO_RELOAD_TIME;
        }
    }
コード例 #9
0
ファイル: World.cs プロジェクト: lordee/godotfps
    // instantly move item to floor
    public void MoveToFloor(Projectile obj)
    {
        // trace downwards
        Transform t  = obj.GlobalTransform;
        RayCast   rc = new RayCast();

        obj.AddChild(rc);
        rc.GlobalTransform = t;
        rc.CastTo          = this.Up * -2000;

        rc.ForceRaycastUpdate();

        if (rc.IsColliding())
        {
            t.origin            = rc.GetCollisionPoint();
            obj.GlobalTransform = t;
        }
        obj.RemoveChild(rc);
    }
コード例 #10
0
    public void Update(RayCast ray)
    {
        // update manually instead only once per frame in process
        ray.ForceRaycastUpdate();
        var isColliding = ray.IsColliding();

        Visible = isColliding;

        if (isColliding)
        {
            Vector3 collisionPoint  = ray.GetCollisionPoint();
            Vector3 collisionNormal = ray.GetCollisionNormal();

            var transform = this.GlobalTransform;
            transform.origin = collisionPoint + collisionNormal * 0.01f;
            GlobalTransform  = transform;

            LookAt(collisionPoint - collisionNormal, GlobalTransform.basis.y.Normalized());
        }
    }
コード例 #11
0
ファイル: Character.cs プロジェクト: CowKeyMan/GodotTutorials
    public override void _PhysicsProcess(float delta)
    {
        Vector3 direction = GetAxisDirection() * speed;

        groundingRay.ForceRaycastUpdate();

        if (groundingRay.IsColliding() && groundingRay.GetCollisionNormal().AngleTo(Vector3.Up) < steepAngle) // check the ngle is not too steep
        {
            Transform t = GlobalTransform;
            t.origin.y      = groundingRay.GetCollisionPoint().y;
            GlobalTransform = t;

            Vector3 normal = groundingRay.GetCollisionNormal();
            Vector3 cross  = GlobalTransform.basis.y.Cross(normal);
            if (cross.Length() > 0.0001f) // If the current player angle is not already at the slope angle
            {
                Rotate(cross.Normalized(), GlobalTransform.basis.y.AngleTo(normal));
            }
            direction = direction.Rotated(Vector3.Up.Cross(normal).Normalized(), Vector3.Up.AngleTo(normal)); // Also rotate the direction
        }
        else
        {
            MoveAndSlide(new Vector3(0, downwardsVelocity, 0));

            // If player is falling, align him
            Vector3 normal = Vector3.Up;
            Vector3 cross  = GlobalTransform.basis.y.Cross(normal);
            if (cross.Length() > 0.0001f) // If the current player angle is not already at the slope angle
            {
                Rotate(cross.Normalized(), GlobalTransform.basis.y.AngleTo(normal));
            }
        }
        MoveAndSlide(direction);
        if (direction.Length() > 0)
        {
            LookAt(GlobalTransform.origin - direction, GlobalTransform.basis.y);
        }
    }
コード例 #12
0
ファイル: Player.cs プロジェクト: starandserpent/Voxel-demo
    public override void _PhysicsProcess(float delta)
    {
        if (ray.IsColliding())
        {
            picker.Pick(ray.GetCollisionPoint(), ray.GetCollisionNormal());
            ray.Enabled = false;
        }

        chunks.Text   = "Chunks: " + Foreman.chunksPlaced;
        vertices.Text = "Vertices: " + Performance.GetMonitor(Performance.Monitor.RenderVerticesInFrame);
        fps.Text      = "FPS: " + Performance.GetMonitor(Performance.Monitor.TimeFps);
        position.Text = "X: " + GlobalTransform.origin.x + "Y: " +
                        GlobalTransform.origin.y + "Z:" + GlobalTransform.origin.z;
        memory.Text = "Memory: " + GC.GetTotalMemory(false) / (1048576) + "MB";

        Vector3 velocity = new Vector3();

        if (Input.IsActionPressed("walk_left"))
        {
            motion.x = 1;
        }
        else if (Input.IsActionPressed("walk_right"))
        {
            motion.x = -1;
        }
        else
        {
            motion.x = 0;
        }

        if (Input.IsActionPressed("walk_forward"))
        {
            motion.z = -1;
        }
        else if (Input.IsActionPressed("walk_backward"))
        {
            motion.z = 1;
        }
        else
        {
            motion.z = 0;
        }

        if (Input.IsActionPressed("move_up"))
        {
            motion.y = 1;
        }
        else if (Input.IsActionPressed("move_down"))
        {
            motion.y = -1;
        }
        else
        {
            motion.y = 0;
        }

        motion = motion.Normalized();

        if (Input.IsActionPressed("move_speed"))
        {
            motion *= 2;
        }

        motion = motion.Rotated(new Vector3(0, 1, 0), Rotation.y - initialRotation.y)
                 .Rotated(new Vector3(1, 0, 0), (float)Math.Cos(Rotation.y) * Rotation.x)
                 .Rotated(new Vector3(0, 0, 1), -(float)Math.Sin(Rotation.y) * Rotation.x);

        velocity = motion * MOVE_SPEED;

        speed.Text = "Movement Speed: " + velocity.Length() + "m/s";

        Vector3 translation = new Vector3(Translation.x + velocity.x, Translation.y + velocity.y,
                                          Translation.z + velocity.z);

        Translation = translation;

        TerraVector3 origin = Converter.ConvertVector(translation);

        marker.MoveTo(origin);
    }
コード例 #13
0
    public override void _Process(float delta)
    {
        // Mouse movement.
        _mouse_motion.y = Clamp(_mouse_motion.y, -1550, 1550);
        Transform t = GlobalTransform;

        t.basis         = new Basis(new Vector3(0, _mouse_motion.x * -0.001f, 0));
        GlobalTransform = t;
        var htr = head.GlobalTransform;

        htr.basis            = new Basis(new Vector3(_mouse_motion.y * -0.001f, 0, 0));
        head.GlobalTransform = htr;

        // Block selection.
        var position = raycast.GetCollisionPoint();
        var normal   = raycast.GetCollisionNormal();

        if (Input.IsActionJustPressed("pick_block"))
        {
            // Block picking.
            var block_global_position = (position - normal / 2).Floor();
            _selected_block = voxel_world.get_block_global_position(block_global_position);
        }
        else
        {
            // Block prev/next keys.
            if (Input.IsActionJustPressed("prev_block"))
            {
                _selected_block -= 1;
            }
            if (Input.IsActionJustPressed("next_block"))
            {
                _selected_block += 1;
            }
            _selected_block = Wrap(_selected_block, 1, 30);
        }
        //  # Set the appropriate texture.
        var     uv      = Chunk.calculate_block_uvs(_selected_block);
        Texture texture = selected_block_texture.Texture;

        if (texture is AtlasTexture atlasTexture)
        {
            atlasTexture.Region = new Rect2(uv[0] * 512, Vector2.One * 64);
        }

        // Block breaking/placing.
        if (crosshair.Visible && raycast.IsColliding())
        {
            var breaking = Input.IsActionJustPressed("break");
            var placing  = Input.IsActionJustPressed("place");
            // Either both buttons were pressed or neither are, so stop.
            if (breaking == placing)
            {
                return;
            }

            if (breaking)
            {
                var block_global_position = (position - normal / 2).Floor();
                voxel_world.set_block_global_position(block_global_position, 0);
            }
            else if (placing)
            {
                var block_global_position = (position + normal / 2).Floor();
                voxel_world.set_block_global_position(block_global_position, _selected_block);
            }
        }
    }
コード例 #14
0
    public override void _PhysicsProcess(float delta)
    {
        if (!IsInstanceValid(target))
        {
            AIState = State.Idle;
            target  = null;
        }

        if (sensors != null)
        {
            for (int at = 0; at < sensors.GetChildCount(); at++)
            {
                RayCast ray = (RayCast)sensors.GetChild(at);
                if (ray != null && ray.IsColliding())
                {
                    Vector3 cpoint   = ray.GetCollisionPoint();
                    Vector3 distance = (cpoint - bot.Translation);
                    distance = bot.Transform.basis.Xform(distance);
                    bot.boost(distance * -0.5f);
                }
            }
        }

        var targetOrigin = new Vector3();

        if (target is Bot)
        {
            targetOrigin = target.GetGlobalTransform().origin;
            var distanceToTarget = (targetOrigin - GetGlobalTransform().origin).Length();
            var relativeVelocity = (target as RigidBody).LinearVelocity - bot.LinearVelocity;
            targetOrigin += relativeVelocity * (distanceToTarget / 300.0f);
        }

        switch (AIState)
        {
        case State.Attacking: {
            float speed = 0.25f;
            if (TurnTowards(targetOrigin))
            {
                speed = 0.5f;
            }
            if (DistanceTo(targetOrigin) > 10)
            {
                bot.boost(new Vector3(0, 0, speed));
            }
            else
            {
                AIState = State.Evading;
            }
            if (AngleTowards(target.Translation) > 0.999f)
            {
                bot.Engage();
            }
        }
        break;

        case State.Evading: {
            Vector3 evasionTarget = bot.Translation - (targetOrigin - bot.Translation);
            float   speed         = 2.0f;
            if (TurnTowards(evasionTarget))
            {
                speed = 1.0f;
            }
            if (DistanceTo(targetOrigin) > 15)
            {
                AIState = State.Attacking;
            }
            else
            {
                bot.boost(new Vector3(0, 0, speed));
            }
        }
        break;

        case State.Avoiding:
            break;
        }
    }
コード例 #15
0
 public override void _Process(float delta)
 {
     Translation = raycast.GetCollisionPoint();
     Rotation    = player.Rotation;
 }
コード例 #16
0
    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();
            }
        }
    }
コード例 #17
0
    private void ProcessInput(float delta)
    {
        //The horizontal movement input from the keyboard, we reset it here so it does not build up a value indefenitely
        inputDirection = Vector3.Zero;
        //Check if the ground ray is colliding then sets the grounded value acordingly
        if (groundRay.IsColliding())
        {
            groundContact = true;
        }
        else
        {
            groundContact = false;
        }

        //Explination for inputDirection below, the inpit direction below
        //Check what movement buttons are pressed
        if (moveForward)
        {
            inputDirection -= Transform.basis.z;
        }
        else if (moveBackward)
        {
            inputDirection += Transform.basis.z;
        }
        if (strafeLeft)
        {
            inputDirection -= Transform.basis.x;
        }
        else if (strafeRight)
        {
            inputDirection += Transform.basis.x;
        }

        //Normalize the input vector to not get faster movement when moving diagonally
        inputDirection = inputDirection.Normalized();

        //If the sprint button is pressed we set sprinting to true
        if (sprint)
        {
            isSprinting = true;
        }
        else
        {
            isSprinting = false;
        }

        //If the player is crouching and the collision shape is a capsule then
        if (crouch)
        {
            //Return out of the above if statement as you cannot crouch while gliding or hooked on a grapple hook point
            if (hasHookPoint || isGliding)
            {
                return;
            }
            //Set the new collision capsule height when crouching
            ((CapsuleShape)bodyCollShape.Shape).Height -= maxCrouchSpeed * delta;
            //Set is crouching to true
            isCrouching = true;
        }
        else if (!isCollidingWithCeiling)
        {
            ((CapsuleShape)bodyCollShape.Shape).Height += maxCrouchSpeed * delta;
            isCrouching = false;
        }
        //Clamp the max and min height for crouching when it is being modified
        ((CapsuleShape)bodyCollShape.Shape).Height = Mathf.Clamp(((CapsuleShape)bodyCollShape.Shape).Height, crouchHeight, defualtHeight);

        //Check if the abillity button is being pressed
        if (!ability)
        {
            abilityPressed = false;
        }
        //If the player presses the ability key for hte grapple
        if (ability && !abilityPressed)
        {
            abilityPressed = true;
            //If the grapple ray is colliding with an object
            if (grappleRay.IsColliding())
            {
                //If the grapple is off
                if (!grappleActive)
                {
                    //Set the grapple active
                    grappleActive = true;
                }
            }
            //If the grapple is active and the the hook point is there then we cut the grapple
            if (grappleActive && hasHookPoint)
            {
                grappleActive    = false;
                hasHookPoint     = false;
                reachedHookPoint = false;
                hookPoint        = new Vector3();
                grappleLine.HideLine();
            }
        }
        //Grapling script to work on later
        if (grappleActive)
        {
            //Check if we already have a hook point for the grapple
            if (!hasHookPoint)
            {
                //If we don't have a hook point yet then we check if the raycast is colliding with something valid
                //If the raycast is colliding we set the hookPoint that point
                hookPoint = grappleRay.GetCollisionPoint();
                //We tell the function we now have a hook point so we don't get a new one in the next interation of the loop
                hasHookPoint = true;
                isGliding    = false;
            }
        }
        //We check if we are colliding with hte ceiling
        if (ceilingRay.IsColliding())
        {
            //If we hit the ceiling with our head we set the graplpling to false to disconect the grapple line
            grappleActive = false;
            //We reset the hookPoint
            hookPoint = new Vector3();
            //We set the hookPointGet
            hasHookPoint = false;
            GlobalTranslate(new Vector3(0, -.2f, 0));
            reachedHookPoint = false;
            grappleLine.HideLine();
        }
        if (reachedHookPoint && groundRay.IsColliding())
        {
            //If we hit the ground we disconect the grapple line
            grappleActive = false;
            //We reset the hookPoint
            hookPoint = new Vector3();
            //We set the hookPointGet
            hasHookPoint     = false;
            reachedHookPoint = false;
            grappleLine.HideLine();
        }

        if (!escape)
        {
            escapePressed = false;
        }
        //  Capturing/Freeing the cursor
        if (escape && !escapePressed)
        {
            escapePressed = true;
            if (Input.GetMouseMode() == Input.MouseMode.Visible)
            {
                Input.SetMouseMode(Input.MouseMode.Captured);
            }
            else
            {
                Input.SetMouseMode(Input.MouseMode.Visible);
            }
        }
    }
コード例 #18
0
    public void PrimaryFire(float Sens)
    {
        if (Sens > 0 && !IsPrimaryFiring)
        {
            IsPrimaryFiring = true;

            if (Inventory[InventorySlot] != null)
            {
                if (Inventory[InventorySlot].Type == Items.TYPE.BUILDABLE)
                {
                    RayCast BuildRayCast = GetNode("SteelCamera/RayCast") as RayCast;
                    if (BuildRayCast.IsColliding())
                    {
                        Tile Base = BuildRayCast.GetCollider() as Tile;
                        if (Base != null && GhostInstance.CanBuild)
                        {
                            Vector3?PlacePosition = Items.TryCalculateBuildPosition(GhostInstance.CurrentMeshType, Base, RotationDegrees.y, BuildRotation, BuildRayCast.GetCollisionPoint());
                            if (PlacePosition != null &&
                                Game.Mode.ShouldPlaceTile(GhostInstance.CurrentMeshType,
                                                          PlacePosition.Value,
                                                          Items.CalculateBuildRotation(GhostInstance.CurrentMeshType, Base, RotationDegrees.y, BuildRotation, BuildRayCast.GetCollisionPoint())))
                            {
                                World.PlaceOn(GhostInstance.CurrentMeshType, Base, RotationDegrees.y, BuildRotation, BuildRayCast.GetCollisionPoint(), 1);                                 //ID 1 for now so all client own all non-default structures
                            }
                        }
                    }
                }

                else if (Inventory[InventorySlot].Type == Items.TYPE.USABLE)
                {
                    Items.UseItem(Inventory[InventorySlot], this);
                }
            }
        }
        if (Sens <= 0 && IsPrimaryFiring)
        {
            IsPrimaryFiring = false;
        }
    }
コード例 #19
0
ファイル: PlayerController.cs プロジェクト: tcmug/spacey
    public override void _PhysicsProcess(float delta)
    {
        Node parent = GetParent();

        if (aimingRay.IsColliding())
        {
            Vector3 cpoint = ToLocal(aimingRay.GetCollisionPoint());
            aimingSight.Translation = cpoint;
            aimingSight.Visible     = true;
        }
        else
        {
            aimingSight.Visible = false;
        }

        if (parent != null)
        {
            PhysicalEntity entity = (PhysicalEntity)parent;

            Vector3 force = new Vector3(0, 0, 0);

            if (Input.IsActionJustPressed("fire"))
            {
                var ent = get_object_under_mouse();
                if (IsInstanceValid(ent))
                {
                    if (IsInstanceValid(target))
                    {
                        target.Deselect();
                    }
                    target = ent;
                    target.Select();
                    (GetParent() as PhysicalEntity).LockOn(ent);
                }
                else
                {
                    (GetParent() as PhysicalEntity).LockOn(null);
                    if (IsInstanceValid(target))
                    {
                        target.Deselect();
                    }
                    target = null;
                }
            }

            if (target != null)
            {
                entity.Engage();
            }

            if (Input.IsActionPressed("fire"))
            {
                entity.Engage();
            }

            if (Input.IsActionPressed("move_forward"))
            {
                force.z += 1;
            }

            if (Input.IsActionPressed("move_backward"))
            {
                force.z += -1;
            }

            if (Input.IsActionPressed("move_left"))
            {
                force.x += 1;
            }

            if (Input.IsActionPressed("move_right"))
            {
                force.x += -1;
            }

            entity.boost(force);

            if (Input.IsActionPressed("rotate_left"))
            {
                torque.z += -1;
            }

            if (Input.IsActionPressed("rotate_right"))
            {
                torque.z += 1;
            }
            Vector3 ret = torque;
            torque = new Vector3();
            entity.turn(ret);
        }
    }
コード例 #20
0
ファイル: Player.cs プロジェクト: Phischermen/GodotFPS
    private void Scan()
    {
        //Get node
        Node node = (Node)PointerProjectRay.GetCollider();

        //Check if scan should be cleared
        if (!PointerProjectRay.IsColliding())
        {
            WantsToClearScan = true;
            ScannedNode      = null;
        }

        if (ScannedNode != node)
        {
            //Player has scanned a new node
            ScannedNode = node;

            //Search for Interactable
            Interactable interactable = node.GetNodeOrNull <Interactable>("Interactable");
            if (interactable != null)
            {
                if (interactable != FocusedInteractable)
                {
                    //New Interactable found
                    ScanPlayer.Play();
                    PlayerReticle.PointingAtInteractable = true;

                    //Change highlight
                    interactable.Highlight = true;
                    if (FocusedInteractable != null)
                    {
                        FocusedInteractable.Highlight = false;
                    }
                }
                WantsToClearScan    = false;
                ScanIsClear         = false;
                FocusedInteractable = interactable;
            }
            else
            {
                //No Interactable Found
                WantsToClearScan = true;
            }
        }
        else if (FocusedInteractable != null)
        {
            //Check if interactable is in range to be interacted with
            PlayerReticle.InteractableOutOfRange = Translation.DistanceTo(PointerProjectRay.GetCollisionPoint()) > InteractThreshold;
        }

        //Check if the scan should be cleared
        if (!ScanIsClear)
        {
            if (WantsToClearScan && ScanTimer.TimeLeft == 0f)
            {
                ScanTimer.Start(ScanTimeout);
            }
            else if (!WantsToClearScan)
            {
                ScanTimer.Stop();
            }
        }
    }
コード例 #21
0
ファイル: Ghost.cs プロジェクト: RedstoneParadox/SkyOfSteel
    public override void _PhysicsProcess(float Delta)
    {
        GhostMesh.Translation     = OldPositions[0];
        GhostMesh.RotationDegrees = OldRotations[0];
        GhostMesh.Visible         = OldVisible[0];

        GhostMesh.Mesh  = Items.Meshes[OldType[0]];
        CurrentMeshType = OldType[0];

        Player Plr = Game.PossessedPlayer;

        OldVisible.RemoveAt(0);
        OldVisible.Add(false);
        if (Plr.Inventory[Plr.InventorySlot] != null)
        {
            RayCast BuildRayCast = Plr.GetNode("SteelCamera/RayCast") as RayCast;
            if (BuildRayCast.IsColliding())
            {
                Tile Base = BuildRayCast.GetCollider() as Tile;
                if (Base != null)
                {
                    Vector3?GhostPosition = Items.TryCalculateBuildPosition(CurrentMeshType, Base, Plr.RotationDegrees.y, Plr.BuildRotation, BuildRayCast.GetCollisionPoint());
                    if (GhostPosition != null)
                    {
                        Vector3 GhostRotation = Items.CalculateBuildRotation(CurrentMeshType, Base, Plr.RotationDegrees.y, Plr.BuildRotation, BuildRayCast.GetCollisionPoint());
                        Translation     = (Vector3)GhostPosition;
                        RotationDegrees = GhostRotation;
                        OldVisible[1]   = true;
                    }
                }
            }
        }
        if (OldVisible[1] == false)
        {
            OldVisible[0]     = false;
            GhostMesh.Visible = false;
        }

        OldCanBuild.RemoveAt(0);
        if (GetOverlappingBodies().Count > 0)
        {
            bool _CanBuild = true;
            foreach (Node Body in GetOverlappingBodies())
            {
                Items.Instance SelectedItem = Game.PossessedPlayer.Inventory[Game.PossessedPlayer.InventorySlot];
                if (SelectedItem != null && Body is Tile && ((Tile)Body).Type == SelectedItem.Id)
                {
                    GhostMesh.MaterialOverride = RedMat;
                    _CanBuild = false;
                }
            }
            OldCanBuild.Add(_CanBuild);
            if (_CanBuild)
            {
                GhostMesh.MaterialOverride = GreenMat;
            }
        }
        else
        {
            GhostMesh.MaterialOverride = GreenMat;
            OldCanBuild.Add(true);
        }
        CanBuild = OldCanBuild[0];

        OldPositions.RemoveAt(0);
        OldPositions.Add(Translation);
        OldRotations.RemoveAt(0);
        OldRotations.Add(RotationDegrees);

        Items.Instance Item = Game.PossessedPlayer.Inventory[Game.PossessedPlayer.InventorySlot];
        if (Item != null && Item.Id != CurrentMeshType)        //null means no item in slot
        {
            OldType.RemoveAt(0);
            OldType.Add(Item.Id);
        }
    }