texts: What's the best way to draw lots of trees

texts:
I'm writing an app which renders a random island planted with trees. The trees are currently two quads, criss-crossed and drawn with textures. I plan to have more complex meshes that form different plant types, e.g. a palm tree, oak, grasses etc..

The problem I face is that because the textures are transparent I must draw them from back to front. Plan-b is to call of using discard in the frag shader, but z-order gives better results:

uniform float uTreeAlpha;
uniform sampler2D uTexture;

varying vec2 vTexCoordOut;

void main (void)
{
  vec4 colour = texture2D(uTexture, vTexCoordOut);
  if (colour.a < 0.1) {
    discard;
  }
  gl_FragColor = vec4(colour.rgb, colour.a * uTreeAlpha);
}

The second problem is because the order changes depending on camera & lookat I do not know an efficient way to draw them in OpenGL in a single call.

At present my rendering code looks like this pseudocode:

if cameraChangedFromLastTime() then
  sortTreesBackToFront();
end
for i = 0 to trees.size() -1
  drawTree()
end

Where every drawTree() sets some uniforms, sets the texture, and then calls glDrawArrays(). I have some optimisations to skip setting a texture or updating texture coords if the last tree and the current are the same, and setting some common uniforms outside the loop, and of skipping trees which are too far away but basically if I have 3000 trees I go 3000 times around the loop.

Drawing each tree individually is the performance killer. If I could draw them in a single call, or batches (while preserving Z-order) I'd probably so in 1/10th the time.

So how would I do that. Bear in mind that my trees are placeholders and eventually I would have:

Different meshes for different trees
Different scales and angles for trees to give some more variety
Different textures for different trees, potentially multiple textures applied to a mesh (e.g. leaves one texture, trunk another)
Trees are all mixed together so no simple way to draw one kind and then another
Some form of simple cyclical animation (branches bobbing in the wind)
All textures would reside in a single atlas

So what's best approach here? Is it feasible to render in a single pass? If I used glDrawElements, rebuilding the indices but not the vertices, could I achieve this?


texts:
Why is the parent that contains 4 children jumping around and then settling into a position instead of rotating once by 90 deg? I can't seem to get it to rotate a single time as expected.
using UnityEngine;

public class rotateparent : MonoBehaviour
{
    public Vector3 rotationPoint;
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            transform.Rotate(new Vector3(0, 0, 1), 90);
        }
    }
}

Object jumping when mouse clicked


texts: How do I animate a spritesheet in cocos2d Android

texts:
I'm trying to animate a sprite in a spritesheet, the goal is to make the character walk from left to right. I subclassed CCSprite: CharacterSprite.

this is my code:

    CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames("WalkAnimation.plist");
    CCSpriteSheet spriteSheet = CCSpriteSheet.spriteSheet("WalkAnimation.png");
    w.addChild(spriteSheet);

    ArrayList<CCSpriteFrame> walkSprites = new ArrayList<CCSpriteFrame>();
    for(int i = 1; i<=8;++i)
    {
        walkSprites.add(CCSpriteFrameCache.sharedSpriteFrameCache().spriteFrameByName("walk"+ i +".png"));
    }
    //float randomFactor = (float)Math.random()*10;
    CCAnimation walkAnimation = CCAnimation.animation("walk", 0.1f, walkSprites);

    Log.v("addEnemy", "Show");
    this.character = CCSprite.sprite(walkSprites.get(0));

    Log.v("addEnemy", "Don't Show");

    this.walkAction = CCRepeatForever.action(CCAnimate.action(walkAnimation, false));
    character.runAction(walkAction);

    for(int k =0; k<amount; k++)
    {
        float randomFactor = (float)Math.random()*10;
        character.setPosition(CGPoint.ccp(-randomFactor * character.getContentSize().width/2, winSize.height / 6.0f));
        spriteSheet.addChild(character);
    }

This code is in my 2nd scene. And whenever I press on Start Game, nothing happens. But the code is executed till:
character = CharacterSprite.sprite("walk1.png");

Can someone provide me of a snippet of animation using a spritesheet?


texts: Unity URP - Batching GPU instanced objects with same material/mesh not working

texts:
I have 100 units (exact same prefab) on screen. The material is a URP Lit using a texture with GPU instancing enabled. Why is it not batching? Am I missing something?

I also noticed it requires 3-4 batches per model, why is this?

See screenshots for stats and info.


texts: Which console systems can indie developers officially develop for?

texts:
As an independent developer, I would like to know what platforms I can use to reach what consoles, and under what prices. I'm assuming a small team (1-3 people) and low or non-existent budget (under $1000).

For the purpose of this question, a "console" is "anything other than a PC." So this includes mobiles phones and other devices.

For this question to be useful and not a collection of every game engine and platform in the world, maybe we should restrict it to technologies that support at least two platforms.


texts: Isometric character from 3D blender model

texts:
I am trying to make a character for an isometric game from a 3D model in Blender. I managed to create a simple humanoid model and implement an isometric camera, rotated by 60° on the x-axis and 45° on the z-axis. Following a screenshot of this model with camera settings:

I chose making a 3D model in blender because I want to be able to make changes to my models without having to change loads of images or sprite sheets and I also wanted to get into 3D modelling.

I looked into articles by clint bellanger - that's where I got the idea to make my graphics in blender, rather than draw in Illustrator or photshop - but I am not sure how I should continue now. My questions are

is this a good way to accomplish my goal of making an isometric character from a 3d model
if it is feasible to turn around the ratio of 2:1 between width and height for my character or if I should render it another way
if the settings of the camera I have in blender are correct to use for an isometric game with a 2:1 ratio of width and height for the tiles.

Thanks in advance


texts: How does one model the sun in a ray tracer?

texts:
How is sun modeled when doing ray-traced rendering? Is it part of the scene, like a sphere with a centre in some far location or it is just considered as a point?

Also regarding sending shadow rays to the sun, is it, again, sampling a sphere or just sending shadow rays to one point?


texts: Bullet Physics - Casting a ray straight down from a rigid body (first person camera)

texts:
I've implemented a first person camera using Bullet--it's a rigid body with a capsule shape. I've only been using Bullet for a few days and physics engines are new to me. I use btRigidBody::setLinearVelocity() to move it and it collides perfectly with the world. The only problem is the Y-value moves freely, which I temporarily solved by setting the Y-value of the translation vector to zero before the body is moved. This works for all cases except when falling from a height.

When the body drops off a tall object, you can still glide around since the translate vector's Y-value is being set to zero, until you stop moving and fall to the ground (the velocity is only set when moving). So to solve this I would like to try casting a ray down from the body to determine the Y-value of the world, and checking the difference between that value and the Y-value of the camera body, and disable or slow down movement if the difference is large enough.

I'm a bit stuck on simply casting a ray and determining the Y-value of the world where it struck. I've implemented this callback:

struct AllRayResultCallback : public btCollisionWorld::RayResultCallback{
    AllRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
        : m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld), m_closestHitFraction(1.0){}

    btVector3   m_rayFromWorld;
    btVector3   m_rayToWorld;
    btVector3   m_hitNormalWorld;
    btVector3   m_hitPointWorld;
    float       m_closestHitFraction;

    virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
    {
        if(rayResult.m_hitFraction < m_closestHitFraction)
            m_closestHitFraction = rayResult.m_hitFraction;

        m_collisionObject = rayResult.m_collisionObject;
        if(normalInWorldSpace){
            m_hitNormalWorld = rayResult.m_hitNormalLocal;
        }
        else{
            m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal;
        }

        m_hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, m_closestHitFraction);
        return 1.0f;
    }
};

And in the movement function, I have this code:

btVector3 from(pos.x, pos.y + 1000, pos.z); // pos is the camera's rigid body position
btVector3 to(pos.x, 0, pos.z); // not sure if 0 is correct for Y

AllRayResultCallback callback(from, to);
Base::getSingletonPtr()->m_btWorld->rayTest(from, to, callback);

So I have the callback.m_hitPointWorld vector, which seems to just show the position of the camera each frame. I've searched Google for examples of casting rays, as well as the Bullet documentation, and it's been hard to just find an example. An example is really all I need.

Or perhaps there is some method in Bullet to keep the rigid body on the ground?

I'm using Ogre3D as a rendering engine, and casting a ray down is quite straightforward with that, however I want to keep all the ray casting within Bullet for simplicity.

Could anyone point me in the right direction? Thanks.


texts:
Why when using this code for the background for my game do I receive blocks with blurred edges?

public final class State_Play extends State_Template {
    private BufferedImage background;
    private int[] pixelelements;
    private int width,height;

    State_Play(){
        init();
    }

    public void init(){
        width=8; //Configuration.appwidth,
        height=6; //Configuration.appheight
        background=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        pixelelements=((DataBufferInt) background.getRaster().getDataBuffer()).getData();
        maketuringarray();
    }

    public void maketuringarray(){
       int singlecolor=new Random().nextInt();
       pixelelements[new Random().nextInt(width*height)]=singlecolor | 0xFF000000;
    }

    @Override
    public void update() {
       maketuringarray();
    }

    @Override
    public void render(Graphics g) {
        g.drawImage(background, 0, 0, Configuration.appwidth, Configuration.appheight, null);
    }

Like this


texts: Quaternion - rotating rigidBody to particular angle over time

texts:
Using Bullet Physics.

There's a rigid body that is rotated.
For some delta-time I need to rotate that body to have rotation of (0, y, 0) - keep the old y value rotation but reset x and z.
The position of the body is described by Quaternion.
And, of course, I can modify the angular velocity.

So, how to calculate what angular velocity should I set for rigidBody to rotate to necessary rotation angle in delta-time?
Seen this article: http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation, but it would be exageration to say if I understand how to implement those formulas...

Here's what I have as initial state of the rigidBody:

 rigidBody.getWorldTransform(tmpM1);
 Quaternion rotation = new Quaternion();
 tmpM1.getRotation(rotation);
 Vector3 angles = new Vector3();
 rotation.getAxisAngle(angles);


texts: Head bone not found when importing .blend to Unity

texts: I have created a model, rigged it(using rigify), and created several actions(animation clips) for it Blender.  Everything seems to be fine.  However, when I import the .blend to Unity I get a console warning that "Required human bone 'Head' not found".  I know that there is a bone called "head" in my .blend.  The animations work, except the head rotation does appear to not be deforming.  Has anyone experienced this? Is this just a naming convention thing.  Should I try to rename my "head" bone to "Head"?  I just don't know the inner workings of the the import process well enough to know what to do.


texts: Handling of persistent key presses in an ECS

texts:
I'm currently in the planning phase of a game. The whole thing should be based on the entity-component-system (ECS) pattern. All logic is concentrated inside of the systems, i.e. that the components hold data only. Communication across the systems is performed using asynchronous events.

Using this design, I'm unable to find a clean solution for the simple example task of moving player:
While the input system generates key press events, I'm looking for a way to query the key state, since the player will most likely want to move the player for more than one frame.

There are two possible ways I can think of solving this problem:

Retrigger the key press event every frame
Pass the corresponding systems a reference to the input system

Neither possibility sounds "correct", since they both require the abuse of the design.

Is there a better approach for solving this issue?


texts:
I am trying to create a file structure for my code in c++classes/Myproject (in UE4 editor). I added a new class and in UE4s "Add C++ Class" dialog box I set the path for the created scripts as MyProject/Source/MyProject/test, test being the subfolder I am trying to create, however when the editor finishes generating the files I get an error saying that it failed to find the files it generated.

...\MyProject\test\SysGen.cpp(4): fatal
error C1083: Cannot open include file: 'test/SysGen.h': No such file
or directory

In visual studio I can see and open the generated scripts, but it fails to compile. What do I need to do for this to work?
here are the files image taken from visual studio:


texts:
I'm creating a procedurally generated planet object in Unity. I start with a cube which is created from 6 meshes (6 sides) and normalize the vertices to get a standard sphere. The problem is that there are visible seams between the meshes. I know if I set the vertex normals to the direction from the center of the sphere to the current vertex then seams will gone but my next step is to add noise to the meshes to generate terrain on the sphere.
What I already tried to remove the seams:

Generating an extra strip around the mesh

Generating an extra strip around the mesh which is located on the adjacent sides

The second solution is almost perfect but seams are still visible a little bit.

When I create the mesh object:

call the built-in RecalculateNormals on the mesh (including the borders)
remove the border vertices, indices and normals
reassign the vertices, indices and normals to the mesh object (excluding the borders)

I use libnoisedotnet to create simplex Perlin noise on the surface:
private MeshData CalculateMeshData()
{
    MeshData meshData = new MeshData();
    meshData.ChunkSize = CHUNK_SIZE;
    meshData.BorderSize = BORDER_SIZE;

    int borderedResolution = meshData.BorderedResolution;
    int vertexIndex = -1;
    float faceWidth = _radius * 2 / CHUNK_SIZE;
    float currentYPosition = -_radius - faceWidth * BORDER_SIZE;

    for (int y = 0; y < borderedResolution; y++)
    {
        float currentXPosition = -_radius - faceWidth * BORDER_SIZE;
        for (int x = 0; x < borderedResolution; x++)
        {
            bool isMeshVertex = !IsBorderVertex(x, y, borderedResolution);
            Vector3 axisAOffset = _axisA * currentXPosition;
            Vector3 axisbOffset = _axisB * currentYPosition;
            Vector3 pointOnUnitCube = _center + axisAOffset + axisbOffset;
            Vector3 vertex = pointOnUnitCube.normalized;
            vertex = vertex * GetElevation(vertex);

            vertexIndex++;
            meshData.AddVertex(vertex, isMeshVertex);

            // Prevents to create more two triangles next to the edge of the mesh.
            if (x != borderedResolution - 1 && y != borderedResolution - 1)
            {
                bool isMeshTriangle = IsMeshTriangle(x, y, borderedResolution);
                meshData.AddTriangle(vertexIndex,
                                     vertexIndex + borderedResolution + 1,
                                     vertexIndex + borderedResolution,
                                     isMeshTriangle);

                meshData.AddTriangle(vertexIndex,
                                 vertexIndex + 1,
                                 vertexIndex + borderedResolution + 1,
                                 isMeshTriangle);
            }

            currentXPosition += faceWidth;
        }

        currentYPosition += faceWidth;
    }

    return meshData;
}

private float GetElevation(Vector3 position)
{
    return 1 + _noise.Evaluate(position) / 10f;
}

Here is the noise library what I tried to use:
https://github.com/SebLague/Procedural-Planets/blob/master/Procedural%20Planet%20E03/Assets/Noise.cs
Is it possible to remove the seams fully?


texts: How would one generate a texture for cracks in different materials?

texts:
I would want to have the ability to simulate different variables like brittleness, or other variables to get varied end results.

I would mainly need to generate impact cracks, so it would need to react to different impact angles and speeds.

I am using ActionScript3, but general theory answers will be helpful as well.


texts: Need help projecting 2D projectile motion in 2.5/isometric 2D game

texts:
So I’ve been researching this a lot and have hit a road block. I’ve read pretty much every thread on here regarding this and while I understand the concept I don’t understand how to implement it. For reference I’m using Godot, but the explanation does not need to be in gdscript or anything.
Basically I have a projectile launcher and an isometric perspective. The best way I can describe what I am trying to achieve is a 8/16 bit Baseball game which many did this quite well. Visually simulating height and 3D physics in a 2D game.
I understand and have in my code the basic kinematic equations. So I can input variables such as initial velocity and the angle. I then get the X and Y position output as variables that update each processing tick, in this case 60 fps.
I’m using kinematic equations because I want to use those values in other places like the total distance and max height.
But this is in a 2D plane, basically from the side view, which would be perfect if I was making a side scroller.
I am having trouble projecting this XY position into the isometric view of my game.
Basically I have a distance and a height of my projectile.


texts: Why do some games persistently have mostly one viable strategy, while others can have many?

texts:
The interesting thing in League of Legends is the existence of the "meta", which, for the purpose of this question, can be defined as the One Strategy That Rules Them All. The meta shifts between patches; but soon after a patch is released, a new variation of the meta emerges and everyone agrees that this particular strategy is, in most cases, objectively best.

It's not that Riot Games doesn't try to migitate this. For instance, they introduced Runes that were supposed to allow personal preferences to be a bigger factor in gameplay – that is, allow a bigger diversity of viable strategies. But most such attempts backfire: there soon emerges the One Correct Rune Page For A Champ anyway.

Oddly, I am told and I read on Internet, this is not the case in Dota 2. (I don't know; I don't play Dota.) According to information I was able to gather, in Dota "nothing is slated in stone" and many heroes can be legitimately played in many roles, there exist multiple viable lane distributions and multiple viable strategies.

This seems counter-intuitive because of another difference between the two games that is frequently pointed out – that is, Dota embraces the concept of hard counters (i.e. if you pick a wrong hero pre-game and are hardly able to be relevant in-game then tough luck, you should've picked another hero), while LoL considers such mechanics broken and instead strives to provide soft counters mostly. Superficially, hard counters would seem to make a game lean towards "slated in stone" strategy (the correct pick is entailed by previous own team and enemy team picks), while soft-counters would seem to allow more diverse strategies thanks to allowing a greater variation of champs to pick in any given situation.

Might I ask, what exactly makes a game have One Strategy To Rule Them All, and what exactly makes a game have multiple viable strategies instead? I provided the examples of LoL and Dota because I think the difference is most striking given the similarity between the two games, but I believe the question easily applies to almost any competitive multiplayer game.


texts: Blend Tree animation problems at rotation

texts:
I have a Blend tree animation  with two floats ( VelocityX, VelocityZ) that have idle, run , run right, run left ,
I use a pad to move it at world space

When VelocityX is -1 it run left, +1 it run right
When VelocityZ is -1 it run back, +1 it run foward

It is working fine but the problem comes when I rotate the character in his Y axis,  If I rotate the character 90 degrees on the Y axis, This system 'breaks' since blend tree is calculating VelocityX and VelocityZ from world space and not local space, So character is doing 'run foward' animation to go top but hi should do 'run right' animation since from character prespective he is moving to the right

How I can implement that local rotation into my blend system?

Any help or guide will be apreciated


texts: How Apple Metal API distinguishes uniforms from vertices buffers?

texts:
I am not sure how metal distinguishes uniforms from vertices buffers?
As far as I know code for passing uniforms in buffers are the same like for vertices:

[self.commandEncoder setVertexBuffer:positionBuffer offset:0 atIndex:0];
[self.commandEncoder setVertexBuffer:uniformBuffer offset:0 atIndex:1];

In shader code there is no keyword defining some struct as uniforms, so how Metal know it? In Opengl GLSL was uniform keyword which was clear for me but I can't figure how it is solved in metal.


texts: How to stop reinitialization in Gamemaker Studio

texts:
Situation: This is a problem that I don't know if it is actually a problem yet: I've got initialization of variables like food, stamina and so forth, in an object called obj_Global_Variables, on its Create Event.

Question: How do I stop it from reinitializing said global variable each time the room is opened? (which, I assume, creates the objects in the room again).


texts: how can I move an actor in opposit direction of mouse's position in GameSalad?

texts:
I have a moving actor named ball and I want to move it in the opposite direction of my mouse's position.

In my code in Move To behaviour for X-axis location I write

  -game.mouse.position.X

and for Y-axis location I write

  -game.mouse.position.Y

But it's not working properly.


texts: Resolving A counters B, who is countered by C, who could be.... in an ATB

texts:
There are 4 player character slots and 8 enemy slots.  I'm using a combat system that's similar to ATB from FF4; You select a move, there's a waiting period depending upon the move, during which other moves can happen, and then it is executed.  The problem is some moves counter other moves and this changes targeting.

Example:

Enemy A is targeting Player 1 with Stampede.  Player 2 decides to use a sweep attack on Enemy A to stop it.  If nothing else happens, this causes Player 2 to become the new target for any damage dealt by Enemy A's Stampede (he's jumping in there and breaking up the attack, if damage is dealt, it's to him now).

Here's the problem: If Player 2 is being countered then he can't counter Enemy A, unless whoever is countering Player 2 is also being countered, in which case he can, unless someone is countering the ... and I'm not sure the cases ever end, even with just the 12 participants.

I need a working theory on how to logic through it smoothly in a pile of code that isn't Mount Everest.  How do I narrow the results until I figure out the exact result?

Using GML if it matters.


texts: Usage of render states in Direct3D 11.x?

texts:
I know there are four different render states. They are

Blend State
Depth Stencil State
Rasterizer State
Sampler State

One of my Direct3D reference books say that Direct3D is a state machine.
But how, where do we use these in game development?


texts:
I am trying to make a 3D game for android using the Rajawali engine to render the 3D graphics and blender for designing my models(exporting as .md2), and I want my character to be able to change weapons, armor, helm, etc.

Rendering every possible animation would be too much: if I had 10 different weapons, 10 armor and 10 helm, I would have to create 1000 animations with every possible equipment and if I add boots to list it would be even worse.

I read somewhere you can use bones for this; but in Android, I only get the object itself to work with.

Does anyone has an idea how i can solve this? If I make the weapon a different object how do I parent it to my models in my game?


texts: My Circle Collider 2D can't pass through Edge Collider 2D

texts:
I'm trying to make Flappy Bird, but when I put an EdgeCollider2Don the Pipe, the bird can't pass through the collider and gets stuck.
Bird code:
{
    Rigidbody2D Rb;
    public float jumpForce;

    float score;

    void Start()
    {
        Rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Rb.velocity = Vector2.up * jumpForce;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.gameObject.tag=="Point")
        {
            score++;
        }
    }
}


texts: Ray tracing - BRDF using Cornell measured spectral data

texts:
I wrote a ray tracer that implements various BRDF models (Oren Nayar, Lamber, Torrance Sparrow and so on).
Now I'm trying to implement a BRDF from measured data.
I choose the Cornell database data available here:

http://www.graphics.cornell.edu/online/measurements/reflectance/spraypaints/index.html

I want to use them because there's a representation of the data as spectrum with 31 sample (my ray tracer use spectral data for light calculation and then convert them to CIE XYZ and then RGB values for the final image rendering).

Which is the correct way to use this data?
Which sample technique must be used?


texts: Unity: GPU Instancing with different textures?

texts:
I'm making use of Unity's GPU Instancing in my 2D game and it really reduces draw calls significantly when using the same Material and same sprite (texture) on all batched gameObjects.
I'm changing colors using MaterialPropertyBlock and everything works fine.
But is there a way to do that with different sprites (textures) on batched gameObjects' material?
What if I used a Sprite atlas to gather all sprites together, will that make GPU Instancing possible with different sprites?
Material's Shader:
Shader "Unlit/UnlitTransparent"
{
Properties
{
    [NoScaleOffset] _MainTex ("Texture", 2D) = "white" {}
    // "PerRendererData" this hides the property from the Material
    inspector (no performance impact, only hides property)
    [PerRendererData] _BaseColor ("Color", Color) = (1, 1, 1, 1)
}
SubShader
{
    Tags { "Queue"="Transparent" "RenderType"="Transparent"
    "IgnoreProjector"="True" "CanUseSpriteAtlas"="True" }
    ZWrite OFF
    Blend SrcAlpha OneMinusSrcAlpha
    LOD 100

    Pass
    {
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag
        // make fog work
        //#pragma multi_compile_fog
        #pragma multi_compile_instancing
        #include "UnityCG.cginc"

        struct appdata
        {
            float4 vertex : POSITION;
            float2 uv : TEXCOORD0;
            UNITY_VERTEX_INPUT_INSTANCE_ID
        };

        struct v2f
        {
            float2 uv : TEXCOORD0;
            //UNITY_FOG_COORDS(1)
            float4 vertex : SV_POSITION;
            UNITY_VERTEX_INPUT_INSTANCE_ID
        };

        UNITY_INSTANCING_BUFFER_START(Props)
            UNITY_DEFINE_INSTANCED_PROP(fixed4, _BaseColor)
        UNITY_INSTANCING_BUFFER_END(Props)

        sampler2D _MainTex;
        float4 _MainTex_ST;

        v2f vert (appdata v)
        {
            v2f o;

            UNITY_SETUP_INSTANCE_ID(v);
            UNITY_TRANSFER_INSTANCE_ID(v, o);

            o.vertex = UnityObjectToClipPos(v.vertex);
            o.uv = v.uv;
            //UNITY_TRANSFER_FOG(o,o.vertex);
            return o;
        }

        fixed4 frag (v2f i) : SV_Target
        {
            UNITY_SETUP_INSTANCE_ID(i);
            // sample the texture
            fixed4 col = tex2D(_MainTex, i.uv) *
            UNITY_ACCESS_INSTANCED_PROP(Props, _BaseColor);
            // apply fog
            //UNITY_APPLY_FOG(i.fogCoord, col);
            return col;
        }
        ENDCG
    }
}
}


texts:
I am new to Augmented reality. I am developing a jewellery try on app with vuforia using unty3D editor.
What I want is to augment a ring on the marker. I download an image(attached bellow) and used it as my marker and it was working fine but when I resized the image in paint to fit to finger the marker stopped augmenting the object.
any help.

What should be the marker size or anything else which I am missing ?
Please help me.


texts: Is it possible to store ALL game data on the sever side

texts:
I want to make a game where everything is supposed to be a surprise. Everything from the maps to the enemies, no guides what so ever.
For a normal player it may not be a big deal but some people may try looking into the game files to find various information.

In order to prevent this, is it possible to store all game files or at least the files that has the info on all the different items, areas, magic spells and such on the server side. In that case, the items and things players unlocked will be stored on the player’s PC and they won’t be able to know details about things they haven’t unlocked yet.

In the case all or at least most game data is stored on the server side, does it even prevent players looking into the game files and will it work on a large scale game.


texts: Defining GUI control event responses using Lua in C++

texts:
I'm using Irrlicht(C++) for a 3D engine, and it has a built in GUI system. The GUI events are something like this:

switch(eventtype)
case button_pressed:
    stuff
case editbox_edited:
    stuff

So far I have begun writing a system that allows me to create the GUIs with Lua scripts. It was very easy to make it so it creates the GUI controls from Lua, but I can not think of a good way to define what should happen when control events occur from Lua too. Here's an example of what I have so far:

Lua:
local button = create_button("button label",10,10,100,50)
toggle_control(button,false)

C++:
static int CreateButton(lua_State* L)
{
 int n = lua_gettop(L);
 core::stringw label = lua_tostring(L,1);
 core::stringw tt((n>=5?lua_tostring(L,6):""));
 int x = lua_tonumber(L,2);
 int y = lua_tonumber(L,3);
 int w = lua_tonumber(L,4);
 int h = lua_tonumber(L,5);
 core::rect r(x,y,x+w,y+h);
 unsigned int id = NextID();
 if(r.isValid())
 {
  gui::IGUIButton* b = device->getGUIEnvironment()->addButton(r,0,0,label.c_str(),tt.c_str());
  cl.insert(ControlPair(id,b));
  lua_pushnumber(L,id);
 }
 else
  lua_pushnumber(L,-1);
 return 1;
}

Please ignore the security issues with the code (it is a very early version). So my question is this: What are some good ways of defining the control events from a script interpreter in C++?


texts: Why is the play button not working on the title screen of my game?

texts:
I'm trying to open up a game demo from my class to see what it looks like, but after opening up the project in Unity, the title screen doesn't work correctly. When I try to click the "Play" button, the game doesn't start.

I'm not sure what's going on because everything was working when the instructor did the demo of this in class and all the files that I downloaded are the same. I also double checked the console messages and no error/warning messages pop up. Below is a screenshot of what I see, as well as a link to the project itself if you'd like to try it out on your own. Thanks in advance!

Here is a link to the project if you want to try it out yourself: https://drive.google.com/file/d/1ekXt948b612dmyT1AZReUOuzh2XbnSDG/view?usp=sharing


texts:
What kind of existing game can be taken as a good source for a 'virtual reality' game, specifically, the one you can play with any 3D VR glasses?

Why do you think this particular game or these games can be adjusted well in the new realm?

Thank you for your thoughts.


texts: How do I make a hitbox for a sword in a top-down game?

texts:
Context: I'm using Box2D through LibGDX in Java. The sword and the player are in separate classes. Both extend LibGDX's Sprite class.

I've got a sword attached to my character that swings when I press 'X' on the keyboard, but I'm having trouble defining its hitbox. I want the hitbox to cover the area that the sword currently is, acting as an extension of my character so it doesn't push him around or slow down his movement. However, when the hero slashes his sword on a wall, I want it to push him back.

The animation:

I want the hitbox to appear only for the duration of the animation (there are only two frames in the animation), then disappear until the sword is swung again.

Would I have to set the hitbox's position to certain coordinates for each frame of the animation in a long switch-case? How could I easily find these coordinates, or is it just trial and error?


texts:
I am developing a space sandbox (3D). Now I am working on an asteroid belt around a planet. I have an Asteroid class and an AsteroidBelt class that has a collection of the Asteroid instances. Each Asteroid object is placed randomly during initialization.

Asteroid class:

Matrix4 transform;
double angle;
float x, y, z;
Vector3 initPosition;

public Asteroid(ModelObject object, Texture diffuseTex){

    initPosition = new Vector3(
            MathUtils.random(-Settings.RingsDepth, Settings.RingsDepth), //x
            MathUtils.random(-.5f, .5f), //y
            MathUtils.random(-Settings.RingsDepth, Settings.RingsDepth)); //z
}

public void update(Camera camera){

    angle += Settings.RingsRotationalSpeed;
    if(angle>360) angle=0;
    if(angle<0) angle = 360;

    double angleRad = angle * MathUtils.degreesToRadians;

    x = (float) (Math.sin(angleRad) * Settings.RingsRadius  + initPosition.x);
    y = initPosition.y;
    z = (float) (Math.cos(angleRad) * Settings.RingsRadius + initPosition.z);

    transform.idt();
    transform.translate(x, y, z);
}

The code above works correctly, but it doesn't allow to rotate the asteroid belt around a planet. How to modify x, y, and z to rotate the asteroid belt around a planet freely? I hope the illustration below will clarify my problem:

Now the asteroid belt looks like below:

But I need to rotate it from -90 to 90 degrees by X and Y axis:

Any help will be appreciated!


texts: How can I efficiently make a solid Texture2D?

texts:
I am trying to programmatically make an Image to cover the entire screen.  I create the Texture2D, then create a Sprite from the Texture2D, then apply the Sprite to my Image. This works, but it is slow.

I suspect the issue is that I am setting each pixel individually for my Texture2D:

private static Texture2D CreateSolidTexture2D(Color color)
{
    var texture = new Texture2D(Screen.width, Screen.height);
    for (int y = 0; y < texture.height; y++)
    {
        for (int x = 0; x < texture.width; x++)
        {
            texture.SetPixel(x, y, color);
        }
    }
    texture.Apply();
    return texture;
}

I have tried creating the Texture2D by resizing a Texture2D of a single pixel, but the color comes out as a translucent white, instead of the color passed:

private static Texture2D CreateSolidTexture2D(Color color)
{
    var texture = new Texture2D(1, 1);
    texture.SetPixel(0, 0, color);
    texture.Resize(Screen.width, Screen.height);
    texture.Apply();
    return texture;
}

Why doesn't my second approach work?  How can I efficiently create a screen-sized Texture2D of a solid color?


texts:
I am doing a 2D sprite based game in XNA for WP7, The game logic is simple, you start at some point, you want to avoid obstacles and reach a certain goal.

obviously I need to make many levels for the game to be challenging and funny.

I am considering making a level editor for my game where I can be able to design the level using some kind of GUI then it translates that to a .lvl or something that the game can read and interpret that to a playable level.

I am asking for an already made level editor for XNA/WP7.


texts:
I have two apps communicating over UDP. One of the apps is a remote control and the other is a robot.

When the robot has some new data, for example a new sensor reading or GPS coordinate, I simply put this in an UDP packet on it's way to the remote for display and that is that. Since the sensor data has a short time span of validity it does not matter when the packet is lost, because a new one will follow with more updated data shortly anyways.

Similarly when the remote wants the robot to change behavior, I put the new desired behavior in an UDP  packet on its way to the remote for execution. The only difference now is that this time I also send an "acknowlegement" packet back to the remote so that it will know that the  the command was well received. Still this is a simple case.

However in the case where there is a state in the robot that BOTH the robot itself and the remote may change, for example if there is a "panic button" that can both be operated from the remote and the robot, how can the state be kept in sync? Since there is no guarantee the UDP packets will reach their destinations, I imagine there needs to be set up some kind of acknowledgement scheme that does not effectuate a command unless it knows that both remote and robot know what is about to happen. But to me this seems impossible to accomplish.


texts: Basic billiards game: Can't detect collision between cuestick and cueball

texts:
I have a basic Unity project on GitHub.

Basically, I have a Cuestick that aims and shoots using the mouse. You can rotate around the cueball with your mouse and when you're ready to shoot, you can hold down the right mouse button and move the mouse forward. The game came follows the cuetip.

However, the collision between the cuestick and cueball is wonky. The cuestick protrudes through the ball and only pushes the ball forward only a little bit.

I've created rigid bodies and colliders for both cuestick and cueball. I've set the cuestick's rigid body to kinematic (if it's unchecked, the poolstick will barely dent the ball). I've tried using OnCollisionEnter and a Debug.Log statement to no avail.

Any help would greatly be appreciated. You can find my scripts in /GameLogic (they're F# sharp scripts whose binaries get compiled and outputted into the /assets folder).


texts: Determine position of a rotated element in Tetris

texts:
Tetris-Tiles are stored as a 4x4 boolean matrix. Each rotation step has it's own matrix, the representation of the T-Block would look like this:

[
    0, 0, 0, 0,
    0, 1, 1, 1,
    0, 0, 1, 0,
    0, 0, 0, 0
],
[
    0, 0, 1, 0,
    0, 0, 1, 1,
    0, 0, 1, 0,
    0, 0, 0, 0
],
[
    0, 0, 1, 0,
    0, 1, 1, 1,
    0, 0, 0, 0,
    0, 0, 0, 0
],
[
    0, 0, 1, 0,
    0, 1, 1, 0,
    0, 0, 1, 0,
    0, 0, 0, 0
]

I'm trying to find a way to calculate the position of the block when it's being rotated and collides with the board (the board is also a matrix). The original Tetris would simply not allow rotation of a block when the rotation would result in a collision. Modern variants of the game will resolve the collision and move the block to a valid position.

Here are some situations that should be solved. The board is 6x6, red = active block, grey = placed/occupied blocks. Each time, a counter-clockwise rotation should be performed. The green overlay indicates the matrix for the block. The arrow indicates the resulting correction to resolve the rotation:

Block is at the left side of the board. Since the block cannot leave the board, it should be moved back inside after a rotation.
Block hits "ground", but isn't placed/committed yet. In this case, the tile must be moved up to resolve the collision (in case of a "I"-Block, the movement would be 2 cells up).
Tile would hit occupied blocks, must be moved left to resolve collision.
Tile cannot be rotated.

What would be the best approach to tackle this problem? Optimally, the solution should be generic, eg. work with arbitrary 4x4 matrix blocks on an arbitrarily sized and populated board.


texts: What is the correct way to raycast on click?

texts:
I am using raycast from screen point to detect if the user has clicked/touched on something.

The following fails 1/10 times; at first I thought due to the raycast missing the subject below, but after adding in the drawline i realise that it randomly doesn't even fire:

// layerMask declared with correct layers
void FixedUpdate(){
    if(Input.GetMouseButtonDown(0)){
        Debug.Log("click");
        Ray ray;
        RaycastHit hit;
        if(Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)){
            Debug.Log("You clicked on " + hit.collider.gameObject.name,hit.collider.gameObject);
        }
}

If I run this in Update() function instead, it will work perfectly - so FixedUpdate() seems to understandably cause the missed clicks... but i'm told I should always run the raycasts in FixedUpdate() for physics optimisation.

Maybe I should split this basic action over 2 functions?

A friend said i need an event handler


texts: OpenGL multiple viewports with 3d-2d viewing

texts:
I am trying to draw two viewports, the one on top having a 3D stuff into it, and the other at bottom with a 2D stuff fed into it. However, whatever 2D stuff i draw in the bottom viewport is not rendered to the screen. Below is the piece of my code.

    void display() {

    //first viewport of height h/8
    glViewport(0, 0, width, height / 8);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    /*glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();*/
    gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(0.0f, 1.0f, 1.0f);
    glRectf(-1.0, 1.0, 1.0, -1.0);
    glFlush();

    //second viewport of height 7h/8
    glViewport(0, 2*height / 8, width, 7 * (height / 8));
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    aspect = (double)8 * width / ((double)height * 7);
    gluPerspective(fieldofview, aspect, nearPlane, farPlane);
    // setup viewing matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.0f, 20.0f, 10.0f,
        0.0f, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    draw_model(objs[0]); // draw the plane
    draw_model(objs[1]); // draw the first diamond
    glPopMatrix();

    glPushMatrix();
    glRotatef(angle, 0.0f, 0.0f, 1.0f);
    glTranslatef(moving_position.x, moving_position.y, moving_position.z);
    draw_model(objs[2]); // draw the second diamond
    glPopMatrix();
    glutSwapBuffers();
    move(8);
    // set up menus
}

void reshape(int x, int y) {
    width = x;
    height = y;
    if (height == 0)        // not divided by zero
        height = 1;
}

void main(int argc, char* argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
    glutInitWindowPosition(position_x, position_y);
    glutInitWindowSize(width, height);
    winId = glutCreateWindow("Mesh Viewer");
    glutReshapeFunc(reshape);
    glutDisplayFunc(display);       // display function
    init();
    glutMainLoop();
}

Below is my output, with no rectangle in 1st viewport:

Moreover, can I apply some background color to the second viewport without using the glScissor?


texts:
I have created a particle system which movement is controlled by a flow field over perlin noise - Available here.

I would be very thankful for any ideas and tips how to control their movement on the Z-plane (noise is 3d), as my 3d knowledge is still very poor.

How to describe the movement controlled by noise value in the third dimension?
I guess the displacement has to be described by a vector directing the movement and added to current possition, but how to determine the z component?

3d example video is available here


texts: How can I make a sprite-sheet-based animation system?

texts:
I want to make animations based on a sprite sheet, but I'm stuck implementing it.

The key things I need my code to do are:

Play through a set of images once (e.g. a jump animation)
Loop through a set of images continuously (e.g. a walking animation)
Change an animation's speed

How can I implement such a system?


texts:
So I'm trying to get my miner drone to mine from the resource by using an Ienumerator but the miner either leaves with more than the capacity or it leaves and it has taken more than the amount of resources available.

So in short, the miner is to head to the resource, when its within the trigger, it needs to take the minerAmount over the miningSpeed amount of time.

Please help.

private void OnTriggerStay(Collider other)
{
    MinableResource mr;
    if (other.CompareTag("Resource"))
    {
        Debug.Log("Within Range of Resource");
        mr = other.GetComponent<MinableResource>();

        if (minerCurrentCapacity < minerMaxCapacity)
        {
            StartCoroutine(MineResource(other));
        }
        else if (minerCurrentCapacity >= minerMaxCapacity)
        {
            minerFull = true;
            Move(storagePos);
        }
    }
}

IEnumerator MineResource(Collider _other)
{
    if (minerFull)
        yield break;

    yield return new WaitForSeconds(miningSpeed);
    Mining(_other);
}

private void Mining(Collider _other)
{
    Debug.Log("Mining");

    MinableResource mr;
    mr = _other.GetComponent<MinableResource>();

    minerCurrentCapacity += miningAmount;
    mr.resources -= miningAmount;

}


texts: Storing and sending English word list using trie data structure

texts:
I was planning on making a word based game something like Scramble or Boggle. I searched on the internet and found that one of the best way to store the Word List is by using a trie.

My question: Is there a way I can pre-make and populate a trie data structure and send it to the user rather than sending him the whole word list and then creating the trie data structure at run-time?


texts:
I'm using the cocos2d-x engine and want to support etc1 on android devices for my game.
For ETC1 i'm using the mali compression tool, and GLSL.

Everything is working, but I can't change the opacity of my sprites anymore.

my alpha blending is GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA .
can anyone help?

Here are one of my Textures with rgb tex + alpha tex

Vertex Shader:

attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_texCoord2;

uniform sampler2D tex1;

void main()
{
    gl_Position = CC_PMatrix * a_position; //CC_PMatrix comes from engine
    v_fragmentColor = a_color;
    v_texCoord = a_texCoord;
    v_texCoord2 = v_texCoord;
}

Fragment Shader:

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
varying vec2 v_texCoord2;

uniform sampler2D u_texture1; //alpha texture

void main()
{
    //CC_Texture0 comes from cocos2d-x engine and represents the rgb
    vec3 tex = texture2D(CC_Texture0, v_texCoord).rgb;
    float alpha = texture2D(u_texture1, v_texCoord).r;

    gl_FragColor = vec4(tex,alpha);
}


texts: Is it okay to update the graphical handlers in the same function where you render them?

texts:
I have a class called 'GraphicalHandler' that all my graphical handlers inherit from the main game loop.
The class manages a static vector of pointers to all instances of itself. I can then call the member fucntion GraphicalHandler::drawAllInstances() to draw everything to the screen.
But since my graphical handlers need to update their graphical objects, as well as rendering them, I figured I would change the function to updateAndDrawAllInstances(). I know that game logic and rendering should be as separated as possible, but since updating the graphical handlers doesn't seem like game logic I figured it would be valid.
So my question is if this is 'accepted' in game development, i.e. to update and render the graphical objects in the same function.


texts: Programatically placing musical notes on a stave

texts:
I'm trying to program a musical stave and have come against the problem of where to place a note, given its index.

The index of a note is defined from a model created from the table in the following: Piano Note Frequencies

For example, in the model, C4 has an index of 40 and D#5 an index of 55.

Here is an image of what the stave currently looks like:

The text in red shows the indices the stave has available to put notes (disregard the horizontal position). Only a few indices are shown, however they extend much further. For example, placing a note on the stave at index 0, it appears at A4 on the stave.

I'm having difficulty translating from an index in the note model, to an index on the musical stave.

At first, I've done a (knowingly) naive implementation. Index 0 in the stave corresponds to A4, or index 49 in the note model. Given an index from the model, calculate how many half steps away the index is and use this as the index in the stave. For example, C5 is index 52 and gives a stave index of 3. Looking at the above image, it's clear this is wrong for two reasons.

Firstly, we didn't account for a note and its sharp laying on the same index. Secondly, we didn't account that B4 and C5 have one half step between them, but are in different places on the stave.

I've been scratching my head over this for a while. What are the rules to follow for translating from a note index to a position on the stave?

EDIT: Each note in the note model knows whether it is sharp or not, its pitch (e.g. C, D, E, etc), and octave.


texts: My game (coded in c++) uses SDL Mixer for its sound. But how do I make certain sounds louder than others. In the game's Main menu, one button is not immediately unlocked, creating a sound if you try to click it. But I can't hear that sound over the game's theme playing in the main menu's background. How do I lower the volume of the game's main theme song in SDL Mixer so I can hear the button press sound?


texts: How to write "Hello World" for N64 purely from scratch?

texts:
As an experiment I want to code a "Hello World" program for N64 using only assembly code, using no headers, tools, helper files, etc.

I just want to write the assembly code bare bones from absolute scratch, assemble it and have it run through a demanding emulator that can show me the output.

I can't find enough info on how to send the correct data to the RSP for video output though. Can anyone offer me a hand here? Not on helping me program, but with information regarding N64's RSP and how to program it to display text, etc.


texts: How to spawn one dummy for each "d" in the message string?

texts:
Im working on a script building game, I have the executor etc done.
However, I have one problem.
To spawn a test dummy, you say pse/d
You can spawn no more than one dummy, how would I make it so if you say pse/d d d d, it spawns as many dummies as there is in the message

EG:
pse/d (Spawns 1 dummy)
pse/d d d d (Spawns 4 dummies)

Current code:

game.Players.PlayerAdded:connect(function(p)
p.Chatted:connect(function(msg)
msg = msg:lower()
if (msg == prefix.."d") then  if (p.Character ~= nil) then
    local d=game.ServerStorage.Dummy:Clone()
    d.Parent=workspace.Debris
    d:MoveTo(p.Character:FindFirstChild'HumanoidRootPart'.Position)
end
end
end)
end) ```


texts:
I've an enemy static tank with a "rotable" cannon turret.
I would like to rotate it in the player's direction .
How to implement it ?
I've thought something like

void Update {
    SearchForPlayer();
    RotateTurret();
}

I don't know how to implement a sort of radar function.
Thanks


texts: Do any of the current gen console or handheld compilers support C++11?

texts: I am not asking for full support but do any of the current gen support C++11? I know VS C++ supports lambda and the auto keyword and I believe gcc supports both as well. Do any of the current gen consoles or handheld (3ds, sony vita) support it?


texts:
Where is a good place to start with learning how to program custom coordinate systems in a 3d environment?

Are there any good books on he topic of gaming coordinate systems? I would like to build a real life data structure based on techniques used for game programming.


texts: IEnumerator Loop not Drawing Changes to Transform.position

texts:
So, I'm working on an IEnumerator() that is called to spawn objects in a fountain style (kinda flying up and out and landing at a random spot nearby).  I feel like I had this working for a hot minute, but I don't know what I've done to screw it up.  It's POSSIBLE that it was only working when it was a void() instead, but I need to function to be a coroutine (or otherwise run on something other than the main thread).

So, I have this.  It works, except you only see the spawned objects after they've landed and the function has exited.

public IEnumerator ThrowFountain()
{
    System.Random rnd = new
    System.Random(System.Guid.NewGuid().GetHashCode());
    GameObject _go = Transform.Instantiate(go, t.position, Quaternion.identity);

    _go.transform.parent = t.parent.transform;
    _go.transform.position = t.position + new Vector3(0.0f, 1.5f, 0.0f);
    float trajectoryHeight = rnd.Next(3,6);
    bool closeEnough = false;

    Vector3 startVec = _go.transform.position;
    Vector3 newVec = new Vector3 (t.position.x + rnd.Next(-6,6), t.position.y, t.position.z + rnd.Next(-6,6));

    float distance = Vector3.Distance(startVec, newVec);
    float startTime = Time.timeSinceLevelLoad;
    float evalTime = startTime;

    while (!closeEnough)
    {
        float distCovered = (evalTime - startTime) * speed;
        float fracJourney = distCovered / distance;
        Vector3 currPos = Vector3.Lerp(startVec, newVec, fracJourney);
        currPos.y += trajectoryHeight * Mathf.Sin(Mathf.Clamp01(distCovered) * Mathf.PI);

        _go.transform.position = currPos;
        closeEnough = V3Close(currPos, newVec, 1.0f);
        Debug.Log("Time: " + Time.time.ToString());
        evalTime += Time.deltaTime;
    }

    yield return new WaitForEndOfFrame();
}

V3Close() just returns a bool so long as none of the vectors of the object and it's target are more than 1.0f apart.  That part seems to be working as well.  Not sure if maybe the IEnumerator loop won't draw the object (because it's not on the main thread or for some other reason)?


texts: Some example of basic algorithms and frameworks used in game creation

texts:
I understand this sounds like a broad topic, I'm asked to have those skill from one of my applied job description.  The thing is that i have been with Unity3d for 2~3 years, but I'm not really sure what are they asking for, it would be the best if you could give me a list of names or some examples to start with.

Thank you.


texts: Retrieve the original prefab from a game object

texts:
How would one proceed to retrieve the original prefab used for instantiating an object?

In the editor these two functions work :

        Debug.Log(PrefabUtility.GetPrefabParent(gameObject));
        Debug.Log(PrefabUtility.GetPrefabObject(gameObject));

But I need something that works in the release version.

I have objects that can be transported between scenes ands I need to save their data and original prefab to be able to instantiate them outside of the scene they have been originally instantiated.

ie:

Game designers create new prefabs.
Game designers create objects from prefabs and place them in scenes (50 to 150 scenes).
Game is played and objects are moved across scenes.
Game is saved and infos about objects which have moved are saved in the save streams (files or network).

This is where I got stuck. Currently, to palliate to the shortcomings, we're saving the name of the prefab in the prefab. But each time a prefab is moved, renamed or duplicated the string must be changed too, sometimes the objects created from the prefab keep the original name (game designer might have edited the prefabPath field).

Maybe there is a better way to achieve proper save games without having to access to the original prefab/name. But currently we keep the saves segmented on a per level basis (easier and safer to save/load to files and transfer the save games to/from servers)


texts:
Just to give you some background info, I'm studying a programming major at a tertiary level and am in my third year, so I'm not a newbie off the street. However, I am still quite new to game programming as a subset of programming. One of my personal projects for next semester is to design and create a 2D platformer game with emphasis on procedural generation and "neato" effects (think metroidvania). I've written up a list of some techniques to help me improve my personal skills (using XNA for the time being). The list is as follows:

QuadTrees:
Build a basic program in XNA that moves basic 2D sprites (circles and squares) around a set path and speed and changes their colour when they collide.
Add functionality to add and delete objects of different sizes (select a direction and speed when adding and just drag and drop them in).
Particles:
Build a basic program in XNA in which you can select different colours and create particle effects of those colours on screen by clicking and dragging the mouse around (simple particles emerging from where the mouse is clicked).
Add functionality where you can change the amount of particles to be drawn and the speed at which they travel and when they expire. Possibly implement gravity and wind after part 3 is complete.
Physics:
Build a basic program in XNA where you have a ball in a set 2D environment, a wind slider, and a gravity slider (can go to negative for reverse gravity). You can click to drag the ball around and release to throw it and, depending on what you do, the ball interacts with the environment.
Implement other shapes afterwards.
Random 2D terrain generation:
Build a basic program in XNA that randomly generates terrain (including hills, caves, etc) created from 2D tiles.
Add functionality that draws the tiles from a tileset and places different tiles depending on where they lie on the y-axis (dirt on top, then rock, then lava, etc).
Randomised objects:
Build a basic program in XNA that, when a button is clicked, displays a randomised item sprite based on parameters (type, colour, etc) with the images pulled from tilesets.
Add the ability to save the item as an object, which stores it in a side-pane where it can be selected for viewing.
Movement:
Build a basic program in XNA where you can move an object around in an environment (tile-based) with a camera that pans with it. No gravity.
Implement gravity and wind, allow the character to jump and fall with some basic platforms.

So my question is this: Are there any other commonly used techniques that I should research, and can I get some suggestions as to the effectiveness of the techniques I've chosen to work on (e.g., don't do QuadTree stuff because [insert reason here], or, do [insert technique here] before you start working on particles because [insert reason here])?

I hope this is clear enough and please let me know if I can further clarify anything!


texts:
I have a game where I would like to register users and post the outcome of matches between two users through web requests in Unity but have some security questions regarding UnityWebRequest.
Assume the following code for sending a web request:
public class TestHTTP : MonoBehaviour
{
    [SerializeField]
    private bool sendRequest = false;
    // Update is called once per frame
    void Update()
    {
        if (sendRequest)
        {
            Model testModel = new Model();
            testModel.ID = "0001";
            testModel.name = "Random_Name";
            testModel.int1 = 555;
            StartCoroutine(SendWebRequest(testModel));
            sendRequest = false;
        }
    }
    public IEnumerator SendWebRequest(Model m)
    {
        string json = JsonUtility.ToJson(m);
        //string text = JsonUtility.ToJson(SimpleAESEncryption.Encrypt(json, "some_password"));
        using (UnityWebRequest request = UnityWebRequest.Post($"some_https", json))
        {
            request.method = UnityWebRequest.kHttpVerbPOST;
            request.SetRequestHeader("Content-Type", "application/json");
            yield return request.SendWebRequest();
            if (request.isNetworkError)
            {
                Debug.Log("NETWORK ERROR:::" + request.error);
            }
            else if (request.isHttpError)
            {
                Debug.Log("HTTP ERROR:::" + request.error);
            }
            else
            {
                string returnData = request.downloadHandler.text;
            }
        };
    }
}

After doing a bit of testing I noted that sending via http would give a plain text body, which was remedied by switching to a https target. Is this enough of a level of encryption or should I add a layer of encryption for the model prior to sending?
Lets assume my model contains data regarding the outcome of a match between two players. Would https (TLS 1.2) be enough to stop someone resending the same request/packet to inflate their number of wins for example? Or should additional measures be taken to stop this?


texts: Why there are no 3D games which allow you to move?

texts:
I've tried many 3D augmented reality games animations vs. all of them were based on this concept: your head is on one reference point, standing still, they only allow you to turn your head and look around, maybe arms and legs are included but you are not allowed to walk around or change your position. Right?

Is this because of the graphic processor has enough competing power to look around but not enough power to calculate depth perception when you also move? Because when you calculated, at least 120hz*1080*1080px*3(RGB)*8bits =3359232000 bits data transfer per second is required for monitoring in 1080p resolution with 120 Hz. When you are standing still, 3+ Giga ram may be enough to store calculated datas of other direction of views to cache but when you are moving it may not be enough right? Because your processor will has more like 3 Ghz clk speed and even in most RISC processors calculating new depth perception will require minimum 2-3 assembly instruction step so the processor chip would not be able to support such calculation because even if it achieves to calculate new perception per pixel in 2 steps it will decrease the speed of construction for whole pix lower to 1.5 GHz and the monitor will require minimum 3.3 GHz(I am not counting the dimming information of BLU or RGBs). So, is this the main issue for this or am I wrong and other concerns are included? If so, what are those?

Thanks.


texts: How to do directional per fragment lighting in world space?

texts: I am attempting to create a GLSL shader for simple, per-fragment directional light.  So far, after following many tutorials, I have continually ran into the issue: my light is specified in world coordinates, however, the shader treats the light's position as being in eye space, thus, the light direction changes when I move the camera.  My question is, how to I transform a directional light position such as (50, 50, 50, 0) into eye space, or, would doing things this way be the incorrect approach to the problem?


texts: How to test a Unity game with different graphics APIs?

texts:
If I don't have a device with Metal, is there a way to test the application with it anyway?
And if my device supports both DirectX and OpenGL, how can I tell the application, for example on Windows, which one should it use?


texts: Behave Plugin : Behavior Tree Perpetually "Running" actions Prempting problem

texts:
I am using the Behave Plugin to make behavior trees for my game

So, I have a behavior tree that looks like this : http://imagebin.org/278510

The Actions marked in Red are basically Perpetually Running actions once reached, they make my guard perpetually rotate in 360 degree circles or 180 degree scans.

This works as expected and everything is fine, however, when a higher priority subtree is introduced things get hairy, So, suppose my higher priority subtree chases the player when he is seen, the guard chases the player eventually loses him, now, I want the patrolSubtree to be completely Re-evaluated (i.e. starting from goToWayPoint) , it will however , come to the patrolSubtree sequence and see that a chain leading to doScanFull is "Running" and will start to rotate the guard "in place" wherever it was when it lost the player.

I believe there should be some way to resolve this, as even in the case of non "Perpetually" running actions, this may cause unexpected behavior when a "Running" action is interrupted by a higher part of the tree.

Can anyone suggest a way to do this ?

I think there should be a way to reset the entire subtree at whim, so that all "Running" actions are cleared, or is there some better way ?

Furthermore, What if I dont want my Top level Selector to be affected by the "Running" state on any Action ? i.e. I want that selector to check every possibility underneath it to see which one to run , that way , if the guard is doing a HalfScan and he sees the player , the "Chase Subtree" will actually evaluate.
    If the Top level Selector was affected by the Running state of stuff under it though, then the higher priority actions may never evaluate because some stuff was in the "Running" state.

Thanks a lot,
Nik


texts: Three levels deep composition (player<-character<-spell), with preset character+skill sets

texts:
So I'm creating a rather generic strategy game similar to Warcraft or League of Legends, which needs to have:

a Player class for representing the users playing the game
a Character class for the character the user is controlling (champions in LoL, heroes in Warcraft)
a Spell class for the spells each character has

Also, each player can own multiple characters, but only one can be active at a time (for now at least...)

So the design issue I'm having is with defining the characters and spells:

I want there to be "presets", similar to how Warcraft and LoL have predefined sets of heroes/champions + spells, i.e. you don't get to choose which spells you want for your character, but you choose a character and it has its own unique spells. And multiple people can pick the same character, in which case they have the same spells too, just on different levels.

First I thought to just create Character and Spell classes, but it's not that simple, since I want it to be easy to define new characters, and defining a character isn't as simple as just creating a new object like this:

char = Character(name='Warrior', spells=[...])

Since I want every player who wants to play "Warrior" to have the same set of spells (every warrior should have FireBall spell while mages have FrostBolt, for example) and same name (Warrior), but different instances.

How should I define something like this? I'm using Python 3.5, but any generic design pattern to solve this is more than welcome.


texts: How to correctly sync an ArrayList of GameObjects on a server/client

texts:
I'm experimenting with networking in Unity and I can't seem to get an ArrayList of GameObjects to sync from the server to the client.

Here is the relevant code:

[SyncVar]
ArrayList walls = new ArrayList();

void Start ()
{
    grid = new bool[width, height];

    if(isServer)
    {
        // This is an algorithm to generate a Maze.
        // It adds the walls of the maze (GameObjects)
        // to the walls array as the algorithm runs.
        CarvePassagesFrom(0, 0, south, grid);
    }
    // If this instance of the game isn't the server, we want to get the
    // already generated maze from the walls ArrayList (that should have synced)
    else
    {
        foreach (GameObject go in walls)
        {
            Debug.Log("Creating game object: " + go);
            Instantiate(go);
        }
    }
}

I have the console tell me how many walls were added in total after the algorithm has run and the walls have definitely been added. But on the client the size of the walls array is 0.

Am I missing something really obvious about the syncing of variables?


texts: Unity 5 Animator controls - What are their Unity 4 correspondent?

texts:
I am following a tutorial that is made with Unity 5, but claims to be compatible with Unity 4.6

I am working with the Animator panel, and I was wondering where could I find certain controls on the Unity 4 version. I highlighted them in a red square.

Basically stuff that has to do with duration of transitions and checking the transition as not having an exit time.


texts: Using 60 frames per second causes the screen to leave a drawn trail of textures, when there is movement

texts:
I'm trying to implement a frame rate feature, and I have noticed that using 60 frames per second causes the screen to leave a drawn trail of textures, when there is movement.

Here's the code I'm using to make the frame rate feature:

public void render(float deltaT){
    currentLevel.updateWorld(deltaT);

    if((fps+=deltaT) >= 1.0/60.0){
        fps = 0;
    }else
        return;

    super.render(deltaT);
    Gdx.gl.glClearColor(103 / 255f, 69 / 255f, 117 / 255f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    currentLevel.updateScreen(deltaT, gameCamera);
}

The currentLevel.updateWorld updates the game's logic.
The currentLevel.updateScreen method updates the camera's position, drawn to the screen.


texts: 2d game with png sequences slowing on Unity3d

texts: We are building a tower defence game,In which enemy movement is done through sprite sheets as well the tower rotation is also done through sprites...every tower and every enemy has its own script attached to it which controle its animation...but when enemies and towers are in greater ammount the games slows down..and become laggy on iphone and unity ..can anyone tell what is the problem with it...


texts: Animator Panel in Unity - Where is "Entry"?

texts:
I am following a tutorial on Unity, and I saw a screenshot like the following:

When I reproduced the steps of the tutorial, I realized that the green "Entry" box was not present on my screen. I have been thinking why this could be and the only reasons that I could think of are:

The tutorial skipped a step
I have something misconfigured
In the latest version of Unity that box has been erased or replaced

Which one is it? Did I forget a 4th option?
PS: If it is option #3, could someone explain me what was this feature for, and what has it been replaced with?
UPDATE I am using Unity 4.6.2f1


texts:
I'm creating an HTML5 game using Canvas, but want to use DOM for the GUI for the reasons mentioned in there articles:

http://blog.sklambert.com/html5-game-tutorial-game-ui-canvas-vs-dom/
http://www.html5gamedevs.com/topic/29569-how-do-you-guys-build-your-ui/
http://www.html5gamedevs.com/topic/802-gui-methodologies/

That being said, we have a component on the GUI that needs to be animated which will be through a sprite. Is it possible to render sprite animations through a DOM element?


texts: Is a separate thread for game loop compulsory for simple games?

texts:
I am new to game development. In order to learn I am recreating this game on android platform. You can observe the game-play video at the above link. It is a simple game.

I have read a lot of articles on getting started with game development.Almost all of them recommended using a game loop on separate thread, which makes sense for other games. However, for this particular game do I need to start a separate thread ?


texts: Explanation of the parameters in the line intersection code

texts:
I am trying to understand a C code that moves the mesh nodes for each time step and i am totally struck on the parameters t1 and t2 please help me sorting this out.
So here is what the function gets (Xa,Ya) (Xb,Yb) (Xc,Yc) and (Xd,Yd) where (Xc,Yc) is the origin (0,0) about which mesh rotates now i have a function that calculates t1 and t2 and (i think t1 is the parameter in barycentre form of line that gives intersection point between two line formed by (Xa,Ya)(Xb,Yb) and (Xc,Yc)(Xd,Yd)) and i have no idea what t2 is...

The code is

static void find_t(real xa, real ya, real xb, real yb,
             real xc, real yc, real xd, real yd,
             real *t1, real *t2, int * flag)
{
  if((xd==xc)&&(xb!=xa))
  {
    if(yd==yc)
    {
      Message0("\nc and d are the same points-aborting!!!\n");
      exit(0);
    }
      (*flag) = 2;
      (*t1) = (xc-xa)/(xb-xa);
      (*t2) = ((yb-ya)*(*t1)-(yc-ya))/(yd-yc);
   }
  else if((xd!=xc)&&(xb==xa))
   {
     if(yb==ya)
     {
        Message0("\na and b are the same points-aborting!!!\n");
        exit(0);
      }
        (*flag) = 2;
        (*t2) = (xc-xa)/(xc-xd);
        (*t1) = ((yd-yc)*(*t2)+(yc-ya))/(yb-ya);
      }
else if((xd==xc)&&(xb==xa))
      {
         (*flag) = 0;
         return;
      }
else
     {
       real k1, k2;
       k1 = (yd-yc)/(xd-xc);
       k2 = (yb-ya)/(xb-xa);
       if(fabs(k2)>=fabs(k1))
   {
     if(k1==k2)
     {
        (*flag) = 0;
        return;
     }
      (*flag) = 1;
      (*t1) = (-k1*(xc-xa)+(yc-ya))/((yb-ya)-k1*(xb-xa));
      (*t2) = ((xb-xa)*(*t1)-(xc-xa))/(xd-xc);
     }
  else
     {
       (*flag) = 1;
       (*t2) = (-k2*(xc-xa)+(yc-ya))/(-(yd-yc)+k2*(xd-xc));
       (*t1) = ((xd-xc)*(*t2)+(xc-xa))/(xb-xa);
     }
    }
       return;
       }

and the value returned is used to update the mesh point if the following condition is satisfied

  if(((flag==1)||(flag==2))&&(t1<=1+cal_small_number(j))&&(t1>=-cal_small_number(j))&&(t2>=0))

  {
     (*x) = (1-t1)*pt1[0] + t1*pt2[0];
     (*y) = (1-t1)*pt1[1] + t1*pt2[1];
      return;

  }

please can some recognize what t2 is and correct me if my thought about t1 is wrong,The point(*x,*y) i get is the intersection point between two lines


texts:
First thing, I am not a seasoned game developer. I am using game development as a conduit to learn programming.

I am attempting to put the player names above the player's head's. I am using a variation of Shawn Hargreaves solution;

            basicEffect.World = Matrix.CreateConstrainedBillboard(textPosition, textPosition - cameraFront, Vector3.Down, null, null);
            basicEffect.View = view;
            basicEffect.Projection = projection;

            const string message = "hello, world!";
            Vector2 textOrigin = spriteFont.MeasureString(message) / 2;
            const float textSize = 0.25f;
            spriteBatch.Begin(0, null, null, DepthStencilState.DepthRead, RasterizerState.CullNone, basicEffect);
            spriteBatch.DrawString(spriteFont, message, Vector2.Zero, Color.White, 0, textOrigin, textSize, 0, 0);
            spriteBatch.End();

My game is space based, so I needed the text to rotate on all 3 axes, so I implemented the following;

        foreach (PlayerShip objPlayerShip in objPlayers)
        {
            Vector3 objTextPosition = objPlayerShip.objShipVector + new Vector3(0, 3, 0);
            Vector3 objCameraFront = objManager.objCamera.objCameraPostion;

            objBasicEffect.World = Matrix.CreateBillboard(objTextPosition, objCameraFront, objManager.objCamera.objCameraUp, null);
            objBasicEffect.View = objManager.objCamera.objViewMatrix;
            objBasicEffect.Projection = objManager.objCamera.objProjectionMatrix;

            string strText = objPlayerShip.strGUID.ToString();
            Vector2 objTextOrgin = objCourierNew.MeasureString(strText) / 2;

            spriteBatch.Begin(0, null, null, DepthStencilState.Default, RasterizerState.CullNone, objBasicEffect);
            spriteBatch.DrawString(objCourierNew, strText, Vector2.Zero, Color.Green, 0, objTextOrgin, 0.09f, SpriteEffects.None, 0.0f);
            spriteBatch.End();

        }

It seems to be working, but the text is upside down. How would I flip the text right side up? I know I have to change something in objBasicEffect.World. I try to tweak it, but I just make things worse...

Any help would be appreciated.
Linuxx


texts:
So I'm making a simple RPG game and I'm currently stuck on creating an attacking module for it.

I need to create a simple attack algorithm but I'm really not very good at it.

Each character has 3 base  states - Attack, Defense, Dexterity

and all characters start off with 50hp and they gain 5hp per level.

What formula should I use to determine chance of hit, and how much damage is dealt? It doesn't have to to too overly complex. Just something simple for now.


texts: How to move a player (with camera) towards a target object until camera fill target object?

texts:
I'm trying to solve this 'algorithm' problem.
I have a player and a camera on it. I want to automatically move this player towards a target object and stop it when target object completely "fit" my camera.
So my question is : how can I find target Vector3 player position, and camera rotation (up/down) to perfectly "view" an object ?
Consider that my target objects are simple Box.
Thanks
Edit:
X is the "right" transform.position to "full" see target object


texts: How can I parse different types of objects from JSON?

texts:
I'm trying to save the player's inventory as a JSON data but I'm having a problem. I have a class Sword which extends an abstract class Weapon which extends another abstract class called Item. This is what JSON file looks like with the Sword and Armor objects in it:

[
    {
        "category": {
            "type": "Weapon",
            "subtype": "Sword"
        },
        "id": 0,
        "value": 1,
        "name": "Wooden Sword",
        "description": "Sword made out of wood",
        "slug": "wooden_sword",
        "stats": {
            "wear": 100,
            "damage": 5
        }
    },
    {
        "category": {
            "type": "Armor",
            "subtype": "Helmet"
        },
        "id": 1337,
        "value": 1,
        "name": "Steel Helmet",
        "description": "Whatever...",
        "slug": "steel_helmet",
        "stats": {
            "wear": 100,
            "defence": 5,
            "vitality": 3,
            "dexterity": -1
        }
    }
]

How can I parse these objects into their respective C# objects, putting the first entry into a Sword object and the second one into a Helmet object. There will be other types of objects in there too, so it's not limited on these two.


texts: How to set the color of a game object as of the other?

texts:
I am 15 year old Indian student and I am creating my first 2D game in Unity. I have set the color of my player as Random and I have to set the color of my game object as of my player. But the color of the player changes Randomly. So I can't set a specific color to my game object.
What I have tried:

public class SetColor : MonoBehaviour {

public GameObject player;
public SpriteRenderer sr;
void Start() {
     sr = GetComponent<SpriteRenderer>();
     sr.color = Color.player;
}

}

But this not worked. Please reply how to code it correctly?


texts: 3D collision avoidance: finding the updated velocity vector (outside the "collision-velocities" cones)

texts:
I am trying to understand and implement the mechanism of a fully 3D collision avoidance (steering behavior) system for flight movement (six degrees of freedom), currently focusing on circumventing static obstacles (all with the shape of a sphere).

However, I don't quite get how to figure it out the new velocity vector of the moving agent. The figure below illustrates the scene. The moving agent (green) has to steer three static objects (blue). The red line represents the initial ahead velocity vector.

Notice that there are also three white/semi-transparent cones. These represent the "forbidden velocity vectors" regarding each obstacle. It means, the set of velocity vectors that, if used as the new ahead vectors of the agent, would make the agent collide with one or more of the obstacles (also note that the radius of each cone is equal the radius of the given obstacle plus the radius of agent, so to allow an offset for the player to maneuver around).

In order to find out the new ahead vector of the moving agent in such 3D environment, considering the three obstacles, a naïve approach would be to simply port to 3D the classic solution explained in this often cited article and exemplified by the following 2D image:

There, a new velocity (orange arrow) is simply calculated by normalizing the minimum distance (black arrow) between the original velocity and the center of the obstacle and then multiplying such normal by the sum between the radius of the obstacle and the radius of the moving agent. Then, an average of the new velocities calculated for each of the obstacles would give the total final velocity.

In many cases, that is sufficient. However, take a look at the cases below (exemplified in 2D to ease visualization):

In all of them, the naïve approach will result in a collision. In a and b, the final new velocity will coincide with the original velocity (red arrow) and the moving agent will move forward despite being partially or fully blocked. In c) and d), the new velocity (orange arrow) will still result in the same consequence.

So, my question is: what is the most computationally efficient way to find out the new ahead vector of the moving agent in such 3D environment, considering the three obstacles, in a way  that avoids collision? Or, in other words, the new ahead vector that:

1) is not inside any of the cones;

2) is the closest possible to the original ahead vector (red line in the picture).

PS: Preferably, I am not looking for a library, I am looking to learn how to that.


texts: What language or platform is used to develop apps for Google+?

texts:
Does anyone know what language or platform is used to develop apps for Google+?

I'm hoping Python, but I know google has a lot of other mediums they could use for this. I'm fine with hearsay as I know the game portion of google+ is pretty new.


texts: Sprite outline based on light position in UE4

texts:
I have simple sprite (for example black box) and I like to add to it outline (red line on example image) but based on light direction. I know UE4 use deffered renderer, so I cant access to lights, but I can pass informations as params to material (angle, distance, intensity...). But still Im not sure how to compute visible corner which is lit by light.

Can you please point me how to achieve this effect?
Thank you.


texts:
I have a body named PersonA. If PersonA collides with another body, the width and height of that body should be saved. I tried it like this but I always get error messages that "Width" and "Height" don't exist.

bool PersonA_OnCollision(Fixture fixtureA, Fixture fixtureB, FarseerPhysics.Dynamics.Contacts.Contact contact)
{
//How tall and broad is the body that collided with PersonA
float Width = fixtureB.Body.Width;
float Height = fixtureB.Body.Height;

return true;
}

How can I get the width and height of another body? What should I change?


texts: Game testing on Android - emulator or real devices?

texts:
I am working at a localization agency and we have been approached by a client about testing their games on iOS as well as Android. Testing on iOS seems fairly easy as we can just buy a couple of devices and we should be covered.
For Android it seems to be completely different. From what i found, the emulator can cover all API levels, screen sizes and such, but i hear it's buggy and nothing could replace testing on real devices. With the vast amount of Android devices out there and the rate at which new devices are released it seems impossible to keep up.
How can i test games (localization and functional) on Android covering all compatible devices?


texts: How to animate a character with props in Blender and then have these props modifiable in Unity3D?

texts:
I have created a fully rigged and fully animated humanoid model in Blender with rigging based on Unity's Mecanim standards for humanoid models.

Now, I want to create custom animation for it in Blender where it's attacking with a sword. I also want to create a sheathing/unsheathing animation.

Also, once the model is imported into Unity, I want to be able to replace the sword and the sheathe props with another model, but still be able to retain the animation.

What's the best way of doing this?

Do I need to modify the rig to include the sword and sheathe meshes? Will adding new bones break my model's compatibility with Mecanim?
If I'm going to add new bones, then that means I will have to include the mesh data of the sword and sheathe to the model, but if that's the case, then how can I replace the sword and sheathe models in Unity if the sword and sheathe are part of the character model?
If the sword and sheathe aren't going to be part of the character armature, then how can I create their animations in Blender which Unity will use?

Fig. 1. The model and its armature.


texts: If I'm designing a melee combo system, should I get the combo animation sprites before coding, or can I code before getting them?

texts:
I intend to make a combo system like Devil May Cry 3 (meaning, combo attacks like E-E-E, or E-(pause)-E-E, and directional attacks like forward+E or backward+E, assuming E is the melee attack button). Right now my pseudocode for the first combo is the following:

var combo_frames = 60
var hitbox_show_frame = 24
var pause_threshold = 45
var hitbox_show_dur_in_frames = 6
var hitbox_consumed = false
var current_frame = 0
var hitbox_show_curr_frame = 0

func _physics_process(delta): #Godot2D's fixedUpdate()
    current_frame += 1
    if current_frame >= hitbox_show_frame and not hitbox_consumed:
        hitbox_coll.disabled = false
        if current_frame >= hitbox_show_frame + hitbox_show_dur_in_frames:
            hitbox_coll.disabled = false
            hitbox_consumed = true
    if frame_num >= combo_frames:
        combo_index = 0
        return Melee_Idle.new()
    pass

func _input(event):
    if hitbox_consumed:
        if current_frame < pause_threshold:
            return Melee_Combo2.new() #normal combo
        elif current_frame < combo_frames:
            return Melee_Combo2_Alt.new() #alternate combo after some delay

As seen, I've implemented a Finite State Machine for the combo system.

However, I don't have the animation sprites for these combos yet, so the frame numbers are just approximations. Should I get or make said animation sprites before designing this combo system, or can I think about it later and use the frame count like above for now?


texts: Update variable before building the unity build

texts:
Before building the standalone build I want to update one of the variables in the script using this.

class MyCustomBuildProcessor : IPreprocessBuild
 {
      public int callbackOrder { get { return 0; } }
      public void OnPreprocessBuild(BuildTarget target, string path) {
        // Do the preprocessing here
        CopyRightCls.buildDateTime = System.DateTime.Now;
        Debug.Log("+++++++++++++++++++++++++++++++++++BuildDateTime" + CopyRightCls.buildDateTime);
      }
 }

But the problem is my date variable is not updating its showing 1 january 0001.


texts: Car physics - velocity and latheral force

texts:
Im developing simple car racing game. To turn a car, I need to calculate slip angles for each tire and then use those angles to find lateral force (using Hans B. Pacejka magic formula). One thing I don't understand is relation between car`s speed and lateral forces.

Everywhere is written, that lateral force depends only on slip angle. But it means that lateral force will be the same for slow and very fast velocity. Is that true? How to use lateral forces to move a car? In my opinion lateral force should be small if velocity is small.


texts: Prefab can't accept script-created material

texts:
I am doing mod support for my game. I want users to be able to change materials of any prefab in the game. In order to achieve that, I create a new material from the imported data and then apply it to an existing prefab.
However, it does not work. It works if I try to assign the newly created material to an object on the scene (not a prefab) and it works if I try to assign an existing material to a prefab. However, assigning a new material to a prefab results in this:

I am fairly certain that is exactly the issue since it can be reproduced as easily as with this snippet of code:
GameObject prefab = Resources.Load("Prefabs/Cubes/IceCube") as GameObject;
prefab.GetComponent<MeshRenderer>().sharedMaterial = new Material(Shader.Find("Standard"));

What am I doing wrong? How can that be worked around?


texts: How to make it so that players can only see one specific player but not the others?

texts:
I'm developing an educational game whose main mechanics are not multiplayer-oriented. However, I would like to add a feature that allows the teacher to enter the game and all students can see him, but no student can see the other students.
Is there a way to do that?


texts:
Something that I can accomplish in 5 minutes in libGDX is taking me forever in Unity. I have a Canvas with a button that covers my entire screen. When the button is clicked, I want the button to fade out and then for the underlying UI to be clickable (if the button is just faded out but it's still on top, you can't click anything).

I tried to use crossFadeAlpha on the Image attached to the button, but the problem is that crossFadeAlpha is async, so I can't do image.enabled = false; when it finishes.

Is there any simple way to accomplish this task in Unity?


texts: Move Camera is an order so that the background doesn't move fast

texts:
I have created a game where I am moving my player on a platform. The car moves fine on the platform and the camera follows the car as well. My problem is that I wanted my background to move slowly. I am using a perspective camera and I am moving camera away to create a zoom out effect when my player jumps. Do you suggest I should move my background towards right so that it creates a simple slow effect? As currently it moves very fast.

here is my video demonstration : https://www.youtube.com/watch?v=xO_mEXo6mNA


texts: Error "glGenBuffers is ambiguous" in Eclipse Mars

texts:
I have called a function, which is part of OpenGL correctly.

uint vboId;
glGenBuffers(1, &vboId);

This is definitely correct because the program successfully runs.

The error shown when I hover over the second line is as follows.

  'glGenBuffers' is ambiguous '
  Candidates are:
  void glGenBuffers(int, unsigned int *)'

The full function is below.

void Loader::storeDataInVao(int position, short data[], ushort data_length) {
    uint vboId;
    glGenBuffers(1, &vboId);
    vbos.push_back(vboId);
    glBindBuffer(GL_ARRAY_BUFFER, vboId);
    glBufferData(GL_ARRAY_BUFFER, data_length * 2, &data, GL_STATIC_DRAW);
    glVertexAttribPointer(position, 2, GL_SHORT, GL_FALSE, 0, 0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}

The includes are "Loader.h", "RawModel.h" and "", two of which are my other files. However, every single one of my header files has valid header guards, defined as shown below.

#ifndef SRC_DISPLAY_LOADER_H_
#define SRC_DISPLAY_LOADER_H_
code here
#endif /* SRC_DISPLAY_LOADER_H_ */

The glGenBuffers is underlined red, just like any other error.


texts: NullReferenceException: Object reference not set to an instance of an object

texts: Hi so im displaying food, health an water on the screen in a text box by using UnityEngine.UI and making text variables. They are all defined in the update function so they will keep changing and are all defined one after another with nothing in between. it will only call the first one there and the others it gives me the error message above.


texts: How can I alleviate network lag issues with players from other countries?

texts:
I am developing a small multiplayer game where players move through the map and interact with each other. The game is written in VB.Net.

When I tested my game with players on a LAN everything worked pretty smoothly. Testing it on the internet with players from the same country worked pretty well, without lag, also. The problem is when players from other countries try to connect to the game: they can connect and play but the game is very laggy for them.

What should I do to fix the lag?


texts: How to generate Bayer matrix of arbitrary size?

texts:
In ordered dithering Bayer matrix is used.

How is that matrix generated? What algorithm can be used to generate matrix of arbitrary size?


texts: Physics engine recommendation which can simulate pool game correctly?

texts:
I'm making a pool-game like game. This game requires correct (or very accurate) reflective bounces.
I tried Box2D and Bullet Physics, but they both have this problem.

If there is a wall on top of this image, red line is expected course of a real ball in a pool-game. But the engines often shows green line course. Especially,

This happens after a slowly moving ball hits the wall.
Sometimes a rapidly moving ball get slower suddenly.

I'm finding a physics engine which can simulate pool-game accurately as much as possible without these problems. Can I get some recommendations? Now I'm digging Newton Game Dynamics, but I am not sure the engine will show what I want. I'm considering the PhysX engine as a next trial, and have to make my own if nothing works. But it's obvious it'll take very long time, so I wish I won't do that.
I'll be very appreciated if you save my time. And of course, solution with Box2D / Bullet Physics are also welcomed.

I am working with C/C++/Objective+C on iOS.

I attach my configuration with Box2D.

Walls

static box shape
linear/angular damping = 0.1
restitution = 1.0
friction = 100
density = 10
bullet = false
fixed rotation = false
inertial scale = 1.0

Balls

dynamic sphere shape
linear/angular damping = 0.1
restitution = 1.0
friction = 100
density = 20
bullet = true
fixed rotation = false
inertial scale = 1.0


texts:
it's been all day I have a problem getting mousewheel events properly in one of my program. I can make a program from scratch and it work properly, however as soon as i do the same things inside this one, nothing seem to work as i want:

#include <iostream>

#include <SDL2/SDL.h>

int    SCREEN_WIDTH = 640;
int    SCREEN_HEIGHT = 480;

SDL_Event e;
SDL_Window* gWindow;

bool initSDL();

bool handleKeys();

void close();

bool initSDL()
{

    if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
    }

    gWindow = SDL_CreateWindow( "Opengl Test",
                                SDL_WINDOWPOS_CENTERED,
                                SDL_WINDOWPOS_CENTERED,
                                SCREEN_WIDTH,
                                SCREEN_HEIGHT,
                                SDL_WINDOW_SHOWN );

    return true;
}

bool handleKeys()
{
    while( SDL_PollEvent( &e ) )
    {
        if ( e.type == SDL_MOUSEWHEEL )
        {
            std::cout << "WhhheeeeeelllllllLLLLLLLLlllllll" << std::endl;
        }

        if  ( e.type           == SDL_QUIT )
        {
            return true;
        }

    }
}

void close()
{
    //Destroy Window
    SDL_DestroyWindow( gWindow );
    gWindow = NULL;

    //Quit SDL subsystem
    SDL_Quit();
}

int main()
{
    if(!initSDL())
    {
    }

    while( !handleKeys() )
    {
    }

    close();
}

I compile with this makefile:

#comment
#Compiler to use:
CC=g++
#Compiler flags:
APPNAME=TutOpengl
OBJ=main.o
#LIBS=-lSDL2
LIBS=-lSDL2
CFLAGS=-c -g -Wall -std=c++11 -I ./src $(LIBS)

all: $(APPNAME)

$(APPNAME): $(OBJ)
    $(CC) $(OBJ) -o $(APPNAME) $(LIBS)

main.o: main.cpp
    $(CC) $(CFLAGS) main.cpp

clean:
    rm -rf *.o $(APPNAME)

Under Ubuntu(14.04), SDL2. I can't get MouseWheel events properly and as of today i'm unable to find out. In the larger program set i get the MOUSEWHEELS events only every now and then like at random. Compiling should give you one warning, thanks in advance if anyone can help.


texts:
I have a prefab that looks like this:

I have created a couple of 'points' in the Hierarchy using 'Create Element' and I would like to attach them to the prefab, however drag and drop over doesn't work. Why is that?


texts: Isn't it redundant to implement both lights and shadows?

texts:
Most games come up with their lighting implementation and their shadow implementation. Due to deferred shading, we are able to simulate lights independent from the scene geometry. But realistic shadows are still a big challenge in game development. They would have to overlap with each other, have soft edges and are calculated in real time to support dynamic scenes.

There is a presentation where the author, Chun-Fu Chao, mentions this about lights and shadows in game development.

  1000 lights without shadow is easy, but 100 lights with shadow is impossible, now.

I wonder where is the problem, at all? I understand that shadow maps and shadow volumes have their problems, though they are very popular. From my understanding, shadows are just the absence of light. So if we use a very dark ambient color, and use deferred shading for handling all light source with easy, wouldn't that result in shadows for free?


texts: Using QuadTree for Procedural Generation

texts:
so I've been trying to start a new project that focuses on procedural room generation similar to what is seen in Binding of Isaac.

I plan to have the code use a QuadTree to help determine where rooms should be placed. Each node in the quad tree represents any of the possible 4 directions the next room can be placed.

The problem is this. I'm not sure where to start when trying to implement the QTree and haven't found good resources on the topic. Most implementations of QuadTrees in a procedural generation context use them for partitioning spaces and placing rooms within the partitioned spaces. Not sure if that's what I want to achieve. I'm also unsure of weather I should be going in this direction or if there's a more optimal solution?