Exemplo n.º 1
0
    public void DeferredEquipItem(Item item)
    {
        if (item == null)
        {
            GD.Print("Actor.DeferredEquipItem: Can't equip null item");
            return;
        }
        if (unarmed)
        {
            StashHand();
        }
        else
        {
            StashItem();
        }

        if (eyes == null)
        {
            GD.Print("Actor.DeferredEquipItem: No eyes.");
            return;
        }

        eyes.AddChild(item);


        item.Mode      = RigidBody.ModeEnum.Static;
        item.Transform = GetItemTransform();
        //item.Translation = new Vector3(HandPosX, HandPosY, HandPosZ);
        activeItem = item;
        activeItem.Equip(this);
        unarmed = false;
        GD.Print("Successfully equipped item " + item.Name);
    }
    private void LayoutObjectAtRandom(Array <PackedScene> tileArray, int min, int max, int altura) //posicionar objeto en lugar aleatorio//array con todos los muros y creame entre una cantidad minima y maxima de muros
    {
        int objectCount = (int)GD.RandRange(min, (double)max + 1);                                 //numero total de objetos que tenemos que crear

        for (int i = 0; i < objectCount; i++)
        {
            Vector3 randomPosition = RandomPosition();//posición aleatoria que recibo de la lista de bloques libres
            Spatial tileChoise     = GetRandomInArray(tileArray);
            _Board.AddChild(tileChoise);
            tileChoise.Translation     = new Vector3(randomPosition.x * 2, altura, randomPosition.z * 2);
            tileChoise.RotationDegrees = new Vector3(0, 180, 0);
        }
    }
Exemplo n.º 3
0
    public void Interact(Node caller)
    {
        if (Mode == ModeEnum.Rigid)
        {
            Mode = ModeEnum.Kinematic;

            var currentTransform = GlobalTransform;
            GetParent().RemoveChild(this);
            var attachPoint = ((Character2)caller).GetAttachPoint();
            if (attachPoint != null)
            {
                attachPoint.AddChild(this);
            }
            else
            {
                caller.AddChild(this);
            }
            GlobalTransform = currentTransform;
        }
        else
        {
            Mode = ModeEnum.Rigid;

            var currentTransform = GlobalTransform;
            GetParent().RemoveChild(this);
            OriginalParent.AddChild(this);
            GlobalTransform = currentTransform;

            Character2 thrower = caller as Character2;
            ApplyCentralImpulse(-thrower.GlobalTransform.basis.z * ThrowStrength);
        }
    }
Exemplo n.º 4
0
        public override void _Ready()
        {
            base._Ready();
            if (Engine.EditorHint)
            {
                return;
            }
            AddChild(_objects = new Spatial {
                Name = "Objects"
            });
            if (ObjectScene == null)
            {
                return;
            }
            var instance = ObjectScene.Instance();

            if (!(instance is Spatial spatial))
            {
                GD.PushWarning("Provided scene is not a spatial!!!");
                return;
            }
            spatial.Visible = false;
            _objects.AddChild(spatial);
            _cachedObjects.Enqueue(spatial);
            valid = true;
        }
Exemplo n.º 5
0
    public void DeferredFire(string name)
    {
        ammo--;
        speaker.PlayEffect(Sound.Effects.RifleShot);
        Item       projectile   = Item.Factory(Item.Types.Bullet, name);
        Projectile proj         = projectile as Projectile;
        Actor      wielderActor = wielder as Actor;

        if (wielderActor != null)
        {
            proj.sender = wielderActor.NodePath();
        }


        Vector3 projectilePosition = ProjectilePosition();
        Vector3 globalPosition     = this.ToGlobal(projectilePosition);

        Spatial gameNode = (Spatial)Session.GameNode();


        Vector3 gamePosition = gameNode.ToLocal(globalPosition);

        projectile.Translation = gamePosition;
        gameNode.AddChild(projectile);

        Transform start       = this.GetGlobalTransform();
        Transform destination = start;

        destination.Translated(new Vector3(0, 0, 1));
        Vector3 impulse = start.origin - destination.origin;

        projectile.SetAxisVelocity(impulse * ImpulseStrength);
    }
Exemplo n.º 6
0
        public static void generate_generic(
            int dof,
            Spatial parent,
            Vector3 origin)
        {
            configure(dof);
            // Create Static base
            StaticBody base_node = generate_base(new Vector3(0.7F, 0.2F, 0.7F));

            List <Spatial> links  = generate_links();
            List <Joint>   joints = generate_joints();

            parent.AddChild(base_node);
            base_node.GlobalTranslate(origin);
            base_node.GlobalRotate(new Vector3(0F, 1F, 0F), rand.RandfRange(-3.14F, 3.14F));

            Joint base_joint = joints[0];

            base_node.AddChild(base_joint);

            for (int i = 1; i < dof; i++)
            {
                Spatial link  = links[i - 1];
                Joint   joint = joints[i];

                link.AddChild(joint);
                base_joint.AddChild(link);
            }
            base_joint.AddChild(links[dof - 1]);

            transform_all(base_node, base_joint);
            // connect_joints(joints, links, base_node, base_joint, dof);
        }
Exemplo n.º 7
0
        private void StartGrab(InputSource inputSource, Spatial target)
        {
            if (GrabActive || target == null || !Godot.Object.IsInstanceValid(target))
            {
                return;
            }

            CurrentGrabbedTarget = target;
            _currentInputSource  = inputSource;

            var targetTransform = CurrentGrabbedTarget.GlobalTransform;

            _manipulator = new Spatial()
            {
                Name = "manipulator"
            };
            inputSource.GetTree().Root.AddChild(_manipulator);
            _manipulator.GlobalTransform = targetTransform;

            _previousParent = CurrentGrabbedTarget.GetParent();
            _previousParent.RemoveChild(CurrentGrabbedTarget);
            _manipulator.AddChild(CurrentGrabbedTarget);
            CurrentGrabbedTarget.GlobalTransform = targetTransform;

            _manipulatorPosInToolSpace       = _currentInputSource.ToLocal(_manipulator.GlobalTransform.origin);
            _manipulatorupInToolSpace        = _currentInputSource.ToLocal(_manipulator.GlobalTransform.basis.y);
            _manipulatorLookAtPosInToolSpace = _currentInputSource.ToLocal(_manipulator.GlobalTransform.origin - _manipulator.GlobalTransform.basis.z);
        }
Exemplo n.º 8
0
 private void instanciarEdificio(int escena)//resibo por parametro la escena que voy a instanciar al llamar a esta función,comienza con 0
 {
     InstanciarCasa      = true;
     edificioInstanciado = (Spatial)edificios[escena].Instance(); //instancio el edificio que esta en el indice 0
     building.AddChild(edificioInstanciado);                      //agrego como nodo hijo
     //await ToSignal(GetTree().CreateTimer(2.0f),"timeout");
 }
Exemplo n.º 9
0
    public void BulletHit(byte damage, Transform bulletTransform)
    {
        _currentHealth -= (sbyte)damage;

        if (_currentHealth <= 0)
        {
            if (DestroyedTarget.Instance() is Spatial clone)
            {
                _brokenTargetHolder.AddChild(clone);

                foreach (var rigid in clone.GetChildren())
                {
                    if (rigid is RigidBody aRigid)
                    {
                        var centerInRigidSpace = _brokenTargetHolder.GlobalTransform.origin - aRigid.GlobalTransform.origin;
                        var direction          = (aRigid.Transform.origin - centerInRigidSpace).Normalized();

                        aRigid.ApplyImpulse(centerInRigidSpace, direction * 12 * damage);
                    }
                }

                _targetRespawnTimer = TARGET_RESPAWN_TIME;

                _targetCollisionShape.Disabled = true;
                Visible = false;
            }
        }
    }
Exemplo n.º 10
0
        public void BulletHit(int damage, Transform bulletTransform)
        {
            _currentHealth -= damage;
            if (_currentHealth > 0)
            {
                return;
            }
            var clone = DestroyedTarget.Instance();

            _brokenTargetHolder.AddChild(clone);
            foreach (var rigid in clone.GetChildren())
            {
                if (!(rigid is RigidBody body))
                {
                    continue;
                }
                var centerRigidSpace = _brokenTargetHolder.GlobalTransform.origin - body.GlobalTransform.origin;
                var direction        = (body.Transform.origin - centerRigidSpace).Normalized();
                body.ApplyImpulse(centerRigidSpace, direction * 12 * damage);
            }

            _targetRespawnTimer            = TargetRespawnTime;
            _targetCollisionShape.Disabled = true;
            Visible = false;
        }
Exemplo n.º 11
0
    public static void SwapSpatialParent(Spatial child, Spatial newParent)
    {
        Transform t = child.GlobalTransform;

        child.GetParent().RemoveChild(child);
        newParent.AddChild(child);
        child.GlobalTransform = t;
    }
Exemplo n.º 12
0
    public void AttachToTarget(Spatial newParent)
    {
        //Transform t = GlobalTransform;
        Node parent = GetParent();

        parent.RemoveChild(this);
        newParent.AddChild(this);
        //GlobalTransform = t;
    }
Exemplo n.º 13
0
 public override void Reload()
 {
     if (!IsLoaded)
     {
         hook = (GrappleHook)grappleHookScene.Instance();
         hookMountPoint.AddChild(hook);
         hook.GlobalTransform = hookMountPoint.GlobalTransform;
         IsLoaded             = true;
     }
 }
Exemplo n.º 14
0
 public virtual void AssignActor(Actor actor, bool addCamera, string headNodePath)
 {
     this.actor = actor;
     head       = FindNode(headNodePath) as KinematicBody;
     if (addCamera)
     {
         camera = new Camera();
         head.AddChild(camera);
     }
 }
Exemplo n.º 15
0
    private void SetBuildPlaceHolder(BuildingType buildingType)
    {
        _currentlyPlacingBuilding = (IBuilding)FarmerHouseScene.Instance();
        _placementMarker          = (PlacementMarker)PlacementMarkerScene.Instance();
        _placementMarker.AttachTo(_currentlyPlacingBuilding);

        var asNode = (Node)_currentlyPlacingBuilding;

        asNode.AddChild(_placementMarker);
        _buildingsParent.AddChild(asNode);
    }
Exemplo n.º 16
0
        private void addTestSphere()
        {
            testSphere      = new Spatial();
            testSphere.Name = "TestSphere";
            var meshInstance = new MeshInstance {
                Mesh  = new SphereMesh(),
                Scale = new Vector3(0.3f, 0.3f, 0.3f)
            };

            testSphere.AddChild(meshInstance);
            GetTree().Root.GetNode("Spatial").AddChild(testSphere);
        }
Exemplo n.º 17
0
    private void Spawn()
    {
        var spawnLocation = Vector3.Forward * (float)(rng.NextDouble() * spawnRadius);

        spawnLocation  = spawnLocation.Rotated(Vector3.Up, (float)(rng.NextDouble() * 360));
        spawnLocation += this.Transform.origin;

        var newEnemy = (KinematicBody)enemyScene.Instance();

        newEnemy.Translation = spawnLocation;
        world.AddChild(newEnemy);
    }
Exemplo n.º 18
0
    public void PutInObject(Spatial body)
    {
        //put projectile in object
        var scene2         = (PackedScene)GD.Load(Resources.ScenePath + Obj.ToString() + ".tscn");
        var sceneInstance2 = (Projectile)scene2.Instance();
        var scale          = sceneInstance2.Scale;

        body.AddChild(sceneInstance2);
        sceneInstance2.GlobalTransform = GlobalTransform;
        sceneInstance2.HasCollision    = false;
        sceneInstance2.GravityScale    = 0;
    }
Exemplo n.º 19
0
    //  // Called every frame. 'delta' is the elapsed time since the previous frame.
    //  public override void _Process(float delta)
    //  {
    //
    //  }


    private void forma1()
    {
        //Random IniciarAleatoriedad = new Random();
        for (int x = 0; x < ancho; x++)
        {
            for (int z = 0; z < largo; z++)
            {
                if (x == 0 || x == ancho - 1 || z == 0 || z == largo - 1)
                {
                    mosaico = (Spatial)Masaicos[4].Instance(); //instancio la escena empaquetada mosaicos
                    mosaicos.AddChild(mosaico);                //agrego el nodo a la escena
                                                               //cambia la posicion de los mosaicos
                    mosaico.Translation = new Vector3
                                          (
                        (x * tileXoffset) - largo + 1,//posición en X

                        //(float)Godot.GD.RandRange(0,1),//posición en Y convierto randRange en float
                        0,

                        (z * tileXoffset) - ancho + 1// posición en Z
                                          );
                }
                else
                {
                    mosaico = (Spatial)Masaicos[0].Instance(); //instancio la escena empaquetada mosaicos
                    mosaicos.AddChild(mosaico);                //agrego el nodo a la escena
                                                               //cambia la posicion de los mosaicos
                    mosaico.Translation = new Vector3
                                          (
                        (x * tileXoffset) - largo + 1,//posición en X

                        //(float)Godot.GD.RandRange(0,1),//posición en Y convierto randRange en float
                        0,

                        (z * tileXoffset) - ancho + 1// posición en Z
                                          );
                }
            }
        }
    }
        public void Launch(LaunchInfo launchInfo)
        {
            if (NextToLaunch == null)
            {
                return;
            }
            _projectileHolder.AddChild(NextToLaunch);
            var toTranslate = launchInfo.Location - NextToLaunch.GlobalTransform.origin;

            NextToLaunch.GlobalTranslate(toTranslate);
            NextToLaunch.LinearVelocity = launchInfo.Velocity;
            NextToLaunch = (RigidBody)ProjectileScene.Instance();
        }
Exemplo n.º 21
0
    void CombinaQuads()
    {
        MeshInstance cube = new MeshInstance
        {
            Name = "Chunk"
        };

        ArrayMesh cubeArray = new ArrayMesh();

        Godot.Collections.Array kids = chunk.GetChildren();
        Material[] materiais         = new Material[kids.Count];

        int contador = 0;

        foreach (MeshInstance meshI in kids)
        {
            Vector3[] vertLocal  = (Vector3[])meshI.Mesh.SurfaceGetArrays(0)[(int)ArrayMesh.ArrayType.Vertex];
            Vector3[] vertGlobal = new Vector3[vertLocal.Length];

            //convertendo as coordenads de locais para globais dos quads
            for (int i = 0; i < vertLocal.Length; i++)
            {
                vertGlobal[i].x = vertLocal[i].x + meshI.Translation.x;
                vertGlobal[i].y = vertLocal[i].y + meshI.Translation.y;
                vertGlobal[i].z = vertLocal[i].z + meshI.Translation.z;
            }

            ArrayMesh combineArray = new ArrayMesh();
            var       arrays       = new Godot.Collections.Array();
            arrays.Resize((int)ArrayMesh.ArrayType.Max);
            arrays[(int)ArrayMesh.ArrayType.Vertex] = vertGlobal;
            arrays[(int)ArrayMesh.ArrayType.Normal] = meshI.Mesh.SurfaceGetArrays(0)[(int)ArrayMesh.ArrayType.Normal];
            arrays[(int)ArrayMesh.ArrayType.TexUv]  = meshI.Mesh.SurfaceGetArrays(0)[(int)ArrayMesh.ArrayType.TexUv];
            arrays[(int)ArrayMesh.ArrayType.Index]  = meshI.Mesh.SurfaceGetArrays(0)[(int)ArrayMesh.ArrayType.Index];

            cubeArray.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
            materiais[contador] = meshI.GetSurfaceMaterial(0);

            meshI.QueueFree();
            contador++;
        }

        cube.Mesh = cubeArray;
        for (int i = 0; i < materiais.Length; i++)
        {
            cube.SetSurfaceMaterial(i, materiais[i]);
        }

        chunk.AddChild(cube);
    }
Exemplo n.º 22
0
    public void DeferredEquipItem(int index)
    {
        if (unarmed)
        {
            StashHand();
        }
        else
        {
            StashItem();
        }

        ItemData dat = inventory.RetrieveItem(index);

        if (dat == null)
        {
            GD.Print("Actor.DeferredEquipItem: Item at index " + index + " was null.");
            return;
        }

        Item item = Item.FromData(dat);

        if (eyes == null)
        {
            GD.Print("Actor.DeferredEquipItem: No eyes.");
            return;
        }

        eyes.AddChild(item);

        item.Mode        = RigidBody.ModeEnum.Static;
        item.Translation = new Vector3(HandPosX, HandPosY, HandPosZ);
        activeItem       = item;
        activeItem.Equip(this);
        unarmed = false;
        GD.Print("Successfully equipped item " + item.Name);
    }
Exemplo n.º 23
0
    public static void DrawSphere(Vector3 globalLocation, Spatial parent, float diameter = 0.05f)
    {
        MeshInstance sphere = new MeshInstance();
        SphereMesh   shape  = new SphereMesh();

        parent.AddChild(sphere);
        Transform placeholder = sphere.GlobalTransform;

        placeholder.origin     = globalLocation;
        sphere.GlobalTransform = placeholder;
        shape.Radius           = diameter / 2.0f;
        shape.Height           = diameter;
        sphere.Mesh            = shape;
        sphere.Visible         = true;
    }
Exemplo n.º 24
0
    public override void FireWeapon()
    {
        var     clone     = _bulletScene.Instance() as BulletScript;
        Spatial sceneRoot = GetTree().Root.GetChildren()[0] as Spatial;

        sceneRoot.AddChild(clone);

        clone.GlobalTransform = this.GlobalTransform;
        clone.Scale           = new Vector3(4, 4, 4);
        clone.BULLET_DAMAGE   = DAMAGE;

        AmmoInWeapon -= 1;

        PlayerNode.CreateSound("Pistol_shot", this.GlobalTransform.origin);
    }
Exemplo n.º 25
0
    public void DeferredFire(string name)
    {
        if (!ExpendAmmo())
        {
            return;
        }

        speaker.PlayEffect(Sound.Effects.RifleShot);
        Item projectile = Item.Factory(Item.Types.Bullet);

        projectile.Name = name;
        Projectile proj = projectile as Projectile;

        if (proj != null)
        {
            proj.healthDamage = healthDamage;
        }

        Actor wielderActor = wielder as Actor;

        if (wielderActor != null)
        {
            proj.sender = wielderActor.NodePath();
        }

        Vector3 projectilePosition = ProjectilePosition();
        Vector3 globalPosition     = this.ToGlobal(projectilePosition);
        Spatial gameNode           = (Spatial)Session.GameNode();

        Vector3 gamePosition = gameNode.ToLocal(globalPosition);

        projectile.Translation = gamePosition;
        gameNode.AddChild(projectile);

        Transform start       = this.GetGlobalTransform();
        Transform destination = start;

        destination.Translated(new Vector3(0, 0, 1));

        Vector3 impulse = start.origin - destination.origin;

        projectile.SetAxisVelocity(impulse * impulseStrength);

        if (requireAmmoToFire && inventory.ItemCount() == 0)
        {
            StartReload();
        }
    }
Exemplo n.º 26
0
        private Spatial GetOrCreate()
        {
            Spatial spatial;

            if (_cachedObjects.Count != 0)
            {
                spatial = _cachedObjects.Dequeue();
                spatial.SetVisible(true);
            }
            else
            {
                spatial = (Spatial)ObjectScene.Instance();
                _objects.AddChild(spatial);
            }
            return(spatial);
        }
Exemplo n.º 27
0
    public void setSkin(int idskin)
    {
        PackedScene s;

        if (idskin < globale.max_skin)
        {
            s = (PackedScene)GD.Load("res://player/skins/skin_" + idskin + ".tscn");
        }
        else
        {
            s = (PackedScene)GD.Load("res://player/skins/skin_0.tscn");
        }
        Spatial skin = (Spatial)s.Instance();

        cube.AddChild(skin);
    }
Exemplo n.º 28
0
        internal IList <Actor> CreateFromPrefab(Guid prefabId, Guid?parentId, CollisionLayer?collisionLayer)
        {
            var     asset  = _app.AssetManager.GetById(prefabId)?.Asset as Node;
            Spatial prefab = asset.Duplicate() as Spatial;

            // restore assigned animation.
            var animationPlayer = asset.GetChild <AnimationPlayer>();

            if (animationPlayer != null)
            {
                var prefabAnimationPlayer = prefab.GetNode <AnimationPlayer>(animationPlayer.Name);
                prefabAnimationPlayer.AssignedAnimation = animationPlayer.AssignedAnimation;
            }

            Spatial parent = GetGameObjectFromParentId(parentId);

            parent.AddChild(prefab);

            // copy animation target mapping
            var sourceMap = prefab.GetChild <PrefabAnimationTargets>();
            var destMap   = asset.GetChild <PrefabAnimationTargets>();

            if (sourceMap != null && destMap != null)
            {
                destMap.AnimationTargets = sourceMap.AnimationTargets;
            }

            // note: actor properties are set in App#ProcessCreatedActors
            var actorList = new List <Actor>();

            MWGOTreeWalker.VisitTree(prefab, go =>
            {
                var collider = go.GetChild <Area>();
                if (collider != null)
                {
                    MREAPI.AppsAPI.LayerApplicator.ApplyLayerToCollider(collisionLayer, collider);
                }

                if (go is Spatial)
                {
                    var newActor = Actor.Instantiate((Spatial)go);
                    actorList.Add(newActor);
                }
            });

            return(actorList);
        }
Exemplo n.º 29
0
    // Called when the node enters the scene tree for the first time.
    public override async void _Ready()
    {
        _camera         = GetNode <Camera>("Rotation_Helper/Camera");
        _rotationHelper = GetNode <Spatial>("Rotation_Helper");
        _flashlight     = GetNode <SpotLight>("Rotation_Helper/Flashlight");

        Input.SetMouseMode(Input.MouseMode.Captured);
        _weaponSlot = GetNode <Spatial>("Rotation_Helper/Weapon_Slot");

        currentWeapon = (Weapon)GD.Load <PackedScene>("res://weapons/GrapplePistol.tscn").Instance();
        _weaponSlot.AddChild(currentWeapon);

        // wait a frame and add player to enemies list
        await ToSignal(GetTree(), "idle_frame");

        GetTree().CallGroup("enemies", "SetPlayer", this);
    }
Exemplo n.º 30
0
        private void AddSphere(Vector3 position)
        {
            var root = GetTree().Root.GetNodeOrNull("Spatial/Collisions2");

            if (root != null)
            {
                var spatial = new Spatial {
                    Translation = position
                };
                var meshInstance = new MeshInstance {
                    Mesh  = new SphereMesh(),
                    Scale = new Vector3(0.2f, 0.2f, 0.2f)
                };
                spatial.AddChild(meshInstance);
                root.AddChild(spatial);
            }
        }