texts: SFML: Monster following player on a straight line

texts:
I've searched for this and found a few topics , usually they used a function normalize and using simple vector subtracting which is ok , but how should I do it in sfml ?
Instead of using:

Movement = p.position() - m.position();

p is the player and m is the monster

I used something like this to move on a straight line:

sf::Vector2f Tail(0,0);
    if((mPlayer.getPosition().y - mMonster.GetInstance().getPosition().y) >= (mPlayer.getPosition().x - mMonster.GetInstance().getPosition().x)){
        //sf::Vector2f Tail(0,0);
        Tail.x = mPlayer.getPosition().x - mMonster.GetInstance().getPosition().x;

    }
    else if((mPlayer.getPosition().y - mMonster.GetInstance().getPosition().y) <= (mPlayer.getPosition().x - mMonster.GetInstance().getPosition().x)){
        //sf::Vector2f Tail(0,0);
        Tail.y = mPlayer.getPosition().y - mMonster.GetInstance().getPosition().y;

    }

    if(!MonsterCollosion())
    mMonster.Move(Tail * (TimePerFrame.asSeconds() * 1/2 ) );

It works ok if the the height = the width for the game window, although I think it's not the best looking game when it comes to a moving monster, since it starts fast and then it gets slower

so what do you guys advise me to do ?


texts: Mixing threads and coroutines in Unity3D Mobile

texts:
I had a coroutine in Unity3D that downloaded a zip from a server, extracted it to the persistent data path, and loaded its contents into memory. The flow looked something like this:

IEnumerator LongCoroutine()
{
    yield return StartCoroutine(DownloadZip());
    ExtractZip();
    yield return StartCoroutine(LoadZipContent());
}

But the ExtractZip() method (which uses the DotNetZip library), is synchronous, takes too long, and leaves me no place to yield during the process.

This resulted in the application being killed (on mobile devices) whenever I tried to extract a large zip, which I assume is due to the main thread becoming unresponsive for too long.

Is this something that mobile OS are known to do (kill the app if a frame takes too long)?

So, I assumed that extracting the zip on a separate thread might solve the problem, and it seems to have worked. I created this class:

public class ThreadedAction
{
    public ThreadedAction(Action action)
    {
        var thread = new Thread(() => {
            if(action != null)
                action();
            _isDone = true;
        });
        thread.Start();
    }

    public IEnumerator WaitForComplete()
    {
        while (!_isDone)
            yield return null;
    }

    private bool _isDone = false;
}

And I use it like this:

IEnumerator LongCoroutine()
{
    yield return StartCoroutine(DownloadZip());
    var extractAction = new ThreadedAction(ExtractZip);
    yield return StartCoroutine(extractAction.WaitForComplete());
    yield return StartCoroutine(LoadZipContent());
}

But I'm still not sure if this is the best way to implement it, or if I need to lock _isDone (not too used to multithreading).

Can something go wrong with this / am I missing something?


texts:
I am trying to make a sling-shot that fires a projectile. I want it to act like the standard sling-shot in angry birds.

So far I managed to get the "pulling" effect, ie. If I draw backwards it fires in the opposite angle of the direction my finger went, and with different speeds depending on how far I dragged the finger from the "start-position".

Touch Code/logic:

@Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        touchPos.set(screenX, screenY, 0);
        camera.unproject(touchPos);
        Vector2 temp = new Vector2(touchPos.x, touchPos.y);

        Vector2 d = temp.sub(startPos); //subtract finger-position from start-position
        float velX = d.x * FIRE_SPEED; //add speed
        float velY = d.y * FIRE_SPEED;
        d.set(velX, velY); // set the velocity

        projectile.setVelocity(d); //send velocity to object
        projectile.setFired(true); //signal the object that its been fired

        return false;
    }

Object Code:

public void update(float delta){
        if(fired){
            pos.x -=  velocity.x * delta; //since I want it to move the opposite direction of where I dragged, I subtract
            pos.y -=  velocity.y * delta;
        }
    }

How would I go about adding gravity here? I want it to shoot in the set direction, then after a certain time/distance I want it to start falling (taking into account the direction so that it looks like real gravity), exactly as in angry birds.


texts: Entity/Component based engine rendering separation from logic

texts:
I noticed in Unity3D that each gameObject(entity) have its own renderer component, as far I understand, such component handle rendering logic.

I wonder if it is a common practice in entity/component based engines, when single entity have renderer components and logic components such as position, behavior altogether in one box?

Such approach sound odd to me, in my understanding entity itself belongs to logic part and shouldn't contain any render specific things inside.

With such approach it is impossible to swap renderers, it would require to rewrite all that customized renderers.

The way I would do it is, that entity would contain only logic specific components, like AI,transform,scripts plus reference to mesh, or sprite.
Then some entity with Camera component would store all references to object that is visible to the camera.
And in order to render all that stuff I would have to pass Camera reference to Renderer class and render all sprites,meshes of visible entities.

Is such approach somehow wrong?


texts: Need help with objects moving toward the player

texts:
I am making a 2D game with simple "gravity": everything is just pulled toward 0,0. The speed at which they accelerate towards it is GravityAcceleration up to MaxGSpeed.

I also want the player to be able to pull these objects too. I'm using Magnitism and MaxSpeed to deal with the acceleration and speed at which the objects move towards the player.

However, it doesn't work, and I have no idea of what I'm doing wrong. The MoveToPlayer function is only called if the player is within 500 units of the object.

Can anyone see where I'm going wrong?

public virtual void Update(GameTime gameTime)
{
    var vectorToSun = new Vector2(0, 0) - Position;
    var distanceToCenter = vectorToSun.Length();

    vectorToSun.Normalize();
    _velocity += vectorToSun * GravityAcceleration * (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (_velocity.Length() > MaxGSpeed)
    {
        _velocity.Normalize();
        _velocity *= MaxGSpeed;
    }

    Position += _velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

    rotation += 0.003f;
}

public void MoveToPlayer(Vector2 playerPos, GameTime gameTime)
{
    var vectorToPlayer = playerPos - Position;

    vectorToPlayer.Normalize();
    _velocity += vectorToPlayer * Magnitism * (float)gameTime.ElapsedGameTime.TotalSeconds;

    if (_velocity.Length() > MaxSpeed)
    {
        _velocity.Normalize();
        _velocity *= MaxSpeed;
    }
}


texts: 2D Tile Game - Smooth Biome Terrain Transitions

texts:
While working on my 2D tile based game, I encountered a problem. I use Perlin Noise to generate the terrain. Some biomes (Desert, Forest, etc) have different flatness values depending on terrain, which causes the end/start of a new biome to have a big cliff because the terrain is different. When 2 biomes have the same flatness, they are fine, but if they are different, this can happen. Is there any way to keep this from happening?

Example (In programmer art)


texts: Using Lerp to zoom in on an object inside an if statement

texts:
I'm trying to zoom in on an object once the raycast hits it in the Update method, I am using the Lerp method to make the camera movement smoother but it's not working properly. The object only lerps for a single frame.

I also tried using a coroutine but the result is still the same. I can't simply just place it outside the if statement because I only need to change the field of view once the raycast hits an object.

Here's a sample of my code :

if (Input.GetMouseButtonDown(0))
        {
            ray = mainCam.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {

                if (hit.collider.tag.Equals("Building"))
                {

                    SetTarget(hit);
                    mainCam.fieldOfView = Mathf.Lerp(mainCam.fieldOfView, newFOV, Time.deltaTime * smooth);
                }
            }
         }


texts: Select all components of certain type in the children Game Objects

texts:
I would like to set programatically the material on a Game Object. The problem is that it has several Child Objects, which many have their own sprite.

I came up with this...

    foreach(Transform child in enemy.transform) {

        SpriteRenderer _spriteRenderer = child.GetComponent<SpriteRenderer>();

        if (_spriteRenderer) {
            _spriteRenderer.material = ...;
        }

    }

...which works, but it is not very pretty. Is there a better way to do this?

Update: I know about GetComponentsInChildren but I need to also get the GameObject that are disabled


texts: Access different vertices of a Mesh Unity 3d

texts: I have a mesh and I want to color each group of vertices with a certain color. If anyone could please advise how this can be done in Unity using coding?


texts: How can I make my players interested in the game lore of my MMORPG?

texts:
In WoW (World of Warcraft), players skip all quest descriptions, and mindlessly spam "auto attack button", ignore the environment, lore, NPCs as they never existed. I.e., they enter a brain dead "mode". If you ask someone of them what he saw, he won't be able to remember a thing. Except the "Lvl 60" number.

I noticed that in my game, if I include lot of mobs i.e. 1 pack for every 10 seconds of distance traveled, the same effect happens. Players ignore all lore and are inflicted with amnesia.

I also noticed that if my dungeon starts empty e.g. the first 30 meters completely barren of mobs, the players go Lore heavy mode and spend every inch and cranny to find everything.

Question: How can I make a player switch to Normal Brain mode (craves for lore) after a group of enemies have been killed?


texts: LWJGL - If I use VBOs what can I do about separate textures?

texts:
So basically this is my problem:
I am creating a game that needs a texture for each object. Now I would use a sprite sheet but the textures are different sizes. I am using VBOs and I need to some how bind the correct textures when calling drawElements. Now I don't know what to do because I don't want to separate each class to its own VBO because that will just make it like 100+ VBO per level which isn't so efficient (or maybe it is?)
Note this is a 2D game but I still want to make it efficient.

Maybe there is some thing I can do with shaders? I am using shaders...

So that is my question:
What Do I Do?

Things I came up with:

Separate the classes to different VBOs (Easy but I am not sure if very efficient)
Use sprite sheets but have a really really big cellsize then just draw big quads with transparent backgrounds.. (Seems like a stupid idea :P)

Thats it.. So I hope you have ideas!

EDIT: I read some where its possible to have an attribute of which texture to use and pass it in as an element and then the fragment shaders use it.. If this is true I'd love if some one could describe it in more detail and add some examples.. (Also if you need to customize the fragment shader please tell me how because I dont know how to write shaders)


texts: Why I have to press the button twice to deactivate the GameObject for the first time?

texts:
game engine:unity3d

scripting language: unityscript

code:

   var setmenu:GameObject;

  var settings_menu:boolean;

   function Start()        {

   settings_menu=false;

  }
   function settingButtonClick(){

  if(settings_menu==false)
  {
  setmenu.SetActive(true);
    settings_menu=true;

  }
         else
  {
  setmenu.SetActive(false);
   settings_menu=false;
   }
 }

The problem is I have to click the UI button twice to SetActive to become false for the 1st time.
But after that when I again  activate and then press to deactivate it works fine with single click.


texts: Does anyone know what technique was used in Minecraft to create shadows?

texts:
Specifically I want to know the technique used to render shadows under animals and players.

I would like to create shadows like that for my own block game but I don't even know what to google.  Any help is appreciated.


texts:
I'm really slow in uptaking this! I have a GameObject with a Rigidbody.  Now I add via AddForce a velocity to the y-axis. But after that, I want to lerp it to zero. But how? My problem is, that I use the velocity also for steering my GameObject

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {

[Header("Movement")]
[SerializeField] private float speed;
[SerializeField] private float steeringPower;
[SerializeField] private float jumpHeigt;

[Header("Physics")]
[SerializeField] private float gravity;

private Rigidbody rigid;

void Start () {
    rigid = GetComponent<Rigidbody> ();
}

void Update () {
    if (Input.GetKeyDown(KeyCode.UpArrow)) {
        rigid.AddForce (Vector3.up * jumpHeigt);
    } else if (Input.GetKeyDown(KeyCode.DownArrow)) {
        rigid.AddForce (Vector3.down * jumpHeigt);
    }
}

void FixedUpdate () {
    rigid.velocity = new Vector3 (Input.GetAxisRaw ("Horizontal") * steeringPower, rigid.velocity.y, speed);

    //lerp rigid.velocity.y to zero here
}
}


texts:
I am currently trying learn javascript in form of HTML5 games. Stuff that I've done so far isn't too fancy since I'm still a beginner. My biggest concern so far has been that I don't really know what is the best way to code since I don't know the pros and cons of different methods, nor I've found any good explanations about them. So far I've been using the worst (and propably easiest) method of all (I think) since I'm just starting out, for example like this:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 640;
var height = 480;
var player = new Player("pic.png", 100, 100, ...);
also some other global vars...

function Player(imgSrc, x, y, ...) {
   this.sprite = new Image();
   this.sprite.src = imgSrc;
   this.x = x;
   this.y = y;
   ...
}
Player.prototype.update = function() {
    // blah blah...
}
Player.prototype.draw = function() {
    // yada yada...
}

function GameLoop() {
   player.update();
   player.draw();
   setTimeout(GameLoop, 1000/60);
}

However, I've seen a few examples on the internet that look interesting, but I don't know how to properly code in these styles, nor do I know if there are names for them. These might not be the best examples but hopefully you'll get the point:

1:

Game = {
   variables: {
      width: 640,
      height: 480,
      stuff: value
      },
   init: function(args) {
      // some stuff here
      },
   update: function(args) {
      // some stuff here
      },
   draw: function(args) {
      // some stuff here
      },
};
// from http://codeincomplete.com/posts/2011/5/14/javascript_pong/

2:

function Game() {
    this.Initialize = function () {

    }
    this.LoadContent = function () {
        this.GameLoop = setInterval(this.RunGameLoop, this.DrawInterval);
    }

    this.RunGameLoop = function (game) {
        this.Update();
        this.Draw();
    }

    this.Update = function () {
        // update
    }

    this.Draw = function () {
        // draw game frame
    }
}
    // from http://www.felinesoft.com/blog/index.php/2010/09/accelerated-game-programming-with-html5-and-canvas/

3:

var engine = {};
engine.canvas = document.getElementById('canvas');
engine.ctx = engine.canvas.getContext('2d');

engine.map = {};
engine.map.draw = function() {
    // draw map
}

engine.player = {};
engine.player.draw = function() {
    // draw player
}
// from http://that-guy.net/articles/

So I guess my questions are:

Which is most CPU efficient, is there any difference between these styles at runtime?
Which one allows for easy expandability?
Which one is the most safe, or at least harder to hack?
Are there any good websites where stuff like this is explained?

or...

Does it all come to just personal preferance? :)


texts: Changing textures on a Model messes up antialiasing? (XNA)

texts:
Here is a code sample:

        blockModel = game.Content.Load<Model>("Models/Cubes/Cube"); //this is a .fbx file, made in blender

        absoluteBlockTransforms = new Matrix[blockModel.Bones.Count];
        blockModel.CopyAbsoluteBoneTransformsTo(absoluteBlockTransforms);

        /*
        foreach (ModelMesh mesh in blockModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.Texture = game.Content.Load<Texture2D>("Textures/Cubes/CubeLayout"); //this is the texture it's already using, but copy-pasted into a different directory
            }
        }*/

This looks fine

Now if I uncomment the lines above, somehow everything gets screwed up?

Somehow just setting the Texture property messes something up, but I'm not sure what exactly (aside from the symptoms).  Note that framerate doesn't actually change; the small difference is just a coincidence.  Also, the multisampling property is set after this is called, so it's not an issue of it somehow changing the graphics property.


texts:
Recently I have tried adding rendering with multiple meshes in my program. This did not go too well. The attempt I currently have goes like this

    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(VERTEX)* nVertices.at(i);
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = 0;
    bd.MiscFlags = 0;
    bd.StructureByteStride = 0;

    vertexData.pSysMem = vertices.at(i);
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;

    dev->CreateBuffer(&bd, &vertexData, &pVBuffer);

looping through the meshes and doing like wise for the index buffer. Similar to this, the render code loops through the mesh data as well:

        UINT stride = sizeof(VERTEX);
        UINT offset = 0;
        devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
        devcon->IASetIndexBuffer(pIBuffer, DXGI_FORMAT_R32_UINT, 0);

        devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        devcon->DrawIndexed(nIndices.at(i), 0, 0);

But all of this only ends up rendering one of the meshes. Does anyone know what I need to change to fix this or whether I need to have a completely different approach? Thanks in advance!


texts: OpenGL 3.3 Core Compatibility with OpenGL 4.x

texts:
Are all OpenGL calls in 3.3 Core and GLSL 330 core shaders valid and functionally equivalent in OpenGL 4.0 through 4.5 core?

I can't seem to find a clear and definitive answer; both in specification and the real world, is code written for 3.3 core going to function in a 4.5 core context? I've currently kept all of my OpenGL renderer code strictly to 3.3 core profile, but I'd like to take advantage of some features that are only available in 4.0+ and 4.4+ if the user's environment supports those contexts. The change-logs of OpenGL seem fairly simple and it doesn't look like anything in 3.3 core has been deprecated in 4.

Are there new requirements OpenGL 4.0 or 4.4 that makes 3.3 core code used in conjunction with new features like tessellation shaders incompatible?


texts: How can I change the gear of my 2D character?

texts:
Is it possible to change the clothes of a 2D character(it's a 2D Windows Phone game) without creating new animations for that character? I want that the player can change the clothes of the character, but the character animations(for example walking, jumping, attacking) should rest the same. The clothes won't affect the character's animations.

I create my animations in Anime Studio Pro. Is it possible to change the clothes without creating new walking, jumping and attacking animations for every single dress?


texts: What are the fundamentals of game development?

texts:
I completely do not understand how a video game can be coded.

I'm a beginner programmer and only have experience writing console applications that do math and what not. I do not understand how these logical processes can make images move on the screen (video games). Obviously if I jumped into a game development book or something like that I would understand but I am currently still getting a grasp of the fundamentals of programming in general. Could anyone give a simple explanation, coding wise, on the jump between making a computer do simple math to making a computer produce amazing graphical programs such as video games? Maybe there are some introductory videos someone can point me to?


texts:
I implemented the minimum translation vector from codezealot's tutorial on SAT (Separating Axis Theorem) but I'm having an issue I can't quite figure out. Here's the example I have:

As you can see in top and bottom left images regardless of the side the of the green car which red car is penetrating the MTV for the red car still remains as a negative number also here is the same example when the front of the red car is facing the opposite direction the number will always be positive.

When the red car is past the half way through the green car it should switch polarity. I thought I'd compensated for this in my code, but apparently not  either that or it's a bug I can find.

Here is my function for finding and returning the MTV, any help would be much appreciated:

Code


texts:
I'm writing a game that needs to save a lot of detailed data (exact trajectories of some entities) to an external file. I want to save drive space and bandwidth by compressing it, but I've never done this, so I don't know if there is a preferred way to do it.

Of course the compression-decompression should not affect the speed of the game too much.


texts: Aligning a gameObject to position and normal of another gameObject inside Unity

texts:
So I am instantiating a GameObject (the one with cities and trees in the image below) and trying to align it to a hex tiles on a Sphere.

So after I instantiate the gameObject, I ray-cast to get it aligned to the tile normal and tile position but its always a slight offset.

    int random = Random.Range(0, middleIceTiles.Count);
    GameObject tile = middleIceTiles[random].getTileGameObject();
    HexCity cityObj = new HexCity(city, "city-" + middleIceTiles[random].getTileName());
    GameObject cityDummy = Instantiate(cityObj.getCityObj(), tile.transform.renderer.bounds.center + new Vector3(0,0.2f,0), Quaternion.identity) as GameObject;

                        //do a raycast here
    RaycastHit hit;
    Vector3 normal = Vector3.zero;
    if (Physics.Raycast(cityDummy.transform.position, cityDummy.transform.up * (-1.0f),out hit, 25.0f))
    {
       if (hit.collider.gameObject == tile.gameObject)
         {
            Debug.Log(" HIT SNOW TILE CITY " +tile.name+ " TILE TEXTURE " +HexTextureInfoDict[tile.name]);
            normal = hit.normal;
         }
    }
   cityDummy.transform.rotation = Quaternion.FromToRotation(Vector3.up, normal);

So I am getting a random hex tile on the sphere. Then instantiating the cityObj to the tile position. Doing a raycast from the cityObj to the tile to get the tileNormal and orienting it to the tile.

So on each level load, the city gets placed on a random hex tile. But currently, the orientation as well as the position is not exact and always at some offset position from the current tile.

What am I doing wrong here? Is there any other way I can achieve this?

Also, one possible solution is to snap the vertices of the hex gameObject to the hex tile itself. So essentially the 6 vertices of the hex tile has to match the 6 vertices of the hex gameObject. Is this possible? I have never dealt with meshes information of gameobjects inside unity before so I am not sure if this would work?

Something I tried was this..

 Mesh TestMesh = testTile.GetComponent<MeshFilter>().mesh;
 Vector3[] vertices = TestMesh.vertices;

And then snap these vertices of the hex tile with vertices of the gameObject that I want to place on it by looping through all points but that doesn't work either..


texts:
I have a cube in my scene. I want to change its color and I wanna server and all players to see it in this color. I have attached script on the cube:

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class Cube : NetworkBehaviour
{
    [SyncVar(hook = "OnColorChanged")]
    public Color myColor;

    void OnColorChanged(Color value)
    {
        GetComponent<Renderer>().material.color = myColor;
        Debug.Log(value + "," + myColor);
    }

    void Update()
    {
        Debug.Log(myColor);
    }
}

I run GameObject.FindWithTag("cube").GetComponent<Cube>().myColor = Color.red;this in my host script when I want to change the color of the cube, but nothing happens.


texts: Camera LookAt position with fixed screen position

texts:
I have a perspective "lookAt-type" camera. I'm trying to compute specific focus point of the camera, which should be placed in the middle of the screen: I also have a custom 3d point in world space, margin values in screen space and camera's tilt as inputs. I want to compute lookAt point, & camera distance with restriction, that input world space point has to be visible in the middle of the free screen space area (not affected by margin values) and it has to have a given tilt.

I'm able to compute this in 2D, but I'm lost in 3D. Any idea how to achieve this? Here's a sketch of the problem, red and blue area's are margin values of 0.5f in both x and y direction.


texts: Data structure for collecting entities for instanced rendering

texts:
My game, a citybuilder, has many simple entities that rendered via glDrawArraysInstanced. A large city has over 600,000 entities, but most of those entities are one of a few hundred meshes. Every frame, I need a way to collect all those entities so that every entity with the same mesh, texture, and shader pass can be rendered with one draw call. Since my game thread is separate from my render thread, I currently use a data structure, which I call the draw buffer, to collect a plan for what order to draw things in.
This data structure has become a real problem. It's essentially a three dimensional chain of pointers to dynamic arrays, with the first dimension being shader pass, the second mesh, and the third texture. Every frame, the game goes through all entities (which are not in any particular order), filters out the ones that aren't in the view frustum, and inserts that mesh's data into the data structure. The draw buffer takes up a lot of memory and is highly fragmented.
I feel like this isn't the right approach, but I'm not sure what the right approach is. I'm trying to figure out if there is a way to do it without storing what I plan to do, but I do think that can be done without multiple passes on the entity list. Maybe I can keep a master version of the data structure without view frustum culling and compute view frustum culling somewhere else. Then I wouldn't have to rebuild the data structure every frame. Instead I would have to update the data structure every time something is added or removed -- fortunately entities never change shader pass, texture or mesh, so entities will always stay in the same place in the master data structure.
I hope this makes sense to someone because it barely makes sense to me. The question is, can I solve this problem with a better data structure, or should I consider a different approach entirely? Thanks for any advice you guys have.


texts:
I am new to OpenGL. I am making a game similar to this, shown in image below. The problem is when I detect collision, i.e cannon ball and ship collide, I play a sound using

PlaySound(TEXT("explode.wav"), NULL, SND_FILENAME);

After the sound is played, my background animation and the whole scene is stuck for a second and then it resumes. Any fix? Please help. It is my project.


texts: Unity: How to make an array of video clips and play them?

texts:
I have 26 video files which I have to put in an array and play for different objects. So far I have written this from what I know:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;

public class videomanager : MonoBehaviour {

    public VideoClip[] vids;

    private VideoPlayer vp;

    // Use this for initialization
    void Start () {

        vids = new VideoClip[25];
        vp = gameObject.GetComponent<VideoPlayer> ();
    }

    // Update is called once per frame
    void Update () {

    }
}

I have attached this script on a plane on which I am playing the video.

Before that, I had 26 different planes, one for each different video, but I think it would be better if I could play them on a single plane and change the video according to logic.

I am not sure how I should load them into my player and play them.


texts:
I'm trying to set up my Unity game for WebGL, but I quickly found out that you can't access your streaming assets as you would in a standalone build. For example, I have a code snippet below of how I load in all of my game's text for localization (i.e. get english translations of all text in my UI).
public void LoadLocalizedText(string fileName) {
        localizedText = new Dictionary<string, string>();
        // StreamingAssetsPath will always be known to unity, regardless of hardware
        string filePath = Path.Combine(Application.streamingAssetsPath, fileName);
        if (File.Exists(filePath)) {
            string dataAsJson = File.ReadAllText(filePath);

            // deserialize text from text to a LocalizationData object
            LocalizationData loadedData = JsonUtility.FromJson<LocalizationData>(dataAsJson);

            for(int i = 0; i < loadedData.texts.Length; i++) {
                localizedText.Add(loadedData.texts[i].key, loadedData.texts[i].value);
            }
        }
        else {
            // ideally would handle this more gracefully, than just throwing an error (e.g. a pop up)
            Debug.LogError("Cannot find file");
        }

        isReady = true;
    }

I've been looking at online examples, and there's a lot of obsolete examples regarding the use of unity's WWW class and php. From what I understand the UnityWebRequest is now the way to go, but I'm confused how to use it with regards to the example above. I'm also trying to figure out how to connect to my SQLite database which is also stored in streamingAssets.
        public SqliteHelper(string databaseFileName) {
        if (Application.platform == RuntimePlatform.WebGLPlayer) {
            // ????????
        }
        else {
            tag = databaseFileName + ":\t";

            string dbPath = Path.Combine(Application.streamingAssetsPath, databaseFileName);
            if (System.IO.File.Exists(dbPath)) {
                dbConnectionString = "URI=file:" + dbPath;
            }
            else {
                Debug.Log ("ERROR: the file DB named " + databaseFileName + " doesn't exist anywhere");
            }
        }
    }

Now that I can't just open an SqliteConnection, I have no idea if there's a c# only solution, or if I have to learn php as suggested from tutorials such as this one. If someone could walk me through how to solve either of these problems I would greatly appreciate it.


texts:
I have been looking at different jobs in the games industry and a lot of the jobs that I have seen advertised are for a "Tool Developer" position. I do not know what this actually is.

Could someone explain what this is to me please? And if anyone has any links to material that would help me understand it more then that would be very much appreciated.


texts: Polygons vs sprites rendering performance in Unity for windows phone 8

texts:
I'm currently building a windows phone 8 game with unity, having 111 (no more no less) sprites being updated each frames. I have a strong overhead in the profiler (70% to 90% minimum) I tried the following to get higher frame rate,

I'm running it with minimum quality settings,
I tried disabling and enabling V-Sync

Finally I managedto get 60Fps, but I still have large overhead. I believe I should have more than 60Fps for such few amount. Moreover, I still have to implement the game logic over this so I'd like some room in my FPS to be able to work.

I was wondering if it would be better in terms of performance to use polygons instead of sprites? As sprites are quite new in Unity, (that would give me around 222 triangles).

Did someone tried to check the performance differences between sprites and actual mesh renderes in Unity when it comes to phones? If so what could be the best option in that case?

FYI : I'm using the Windows Phone 8 emulator on Visual studio, I have a compliant computer for that so it should normally reflect the behavior of a real phone (expecting some differences but still...)

EDIT : To clarify my question i wonder what is the most efficient in windows phone 8 : Sprites or Mesh renderers?


texts: Assigning multiple game objects to a single sprite (Unity)

texts: I've been making a pokemon game clone on my own with Unity, as I'm a beginner and just trying to learn. Up until now I've been splicing the town pictures and manually putting them together, but this is extremely time consuming and takes several hours. Unity won't let me drag multiple sprites onto the scene, so I have to find another way. So currently my idea is to keep the image of the town as a single sprite, drag it onto the scene, and break it up into 16x16 pixel game objects, so I can add colliders and triggers and what not to each of the game objects. I found a way on the Internet to break up a single sprite into an array of sprites, but I don't know how to lay them out onto the scene. Can someone point me in the right direction and give some help? Thanks


texts: For best practice, which "glTexParameters" should I set when creating a texture?

texts:
For best practice, which glTexParameters should I set when creating a texture?

I am already using a mipmap and anisotropic filtering, but I am not sure if this is enough for each texture or if I should also define some parameters for magnifying and minimizing (i.e. GL_TEXTURE_MIN_FILTER, GL_TEXTURE_MAG_FILTER, etc).

I am creating a texture for a simple game engine I am writing.


texts:
I'm trying to hook lua-scripts to my entities, where several entities of the same type want to use a separate instance of the same script. Problem is, when I run two or more scripts and use any C-api functionality, I get an access violation after some time. I'm guessing some kind of stack corruption occurs but I'm not sure. The application is single-threaded but uses lua_newthread for each entity, and I then use lua_resume on each new thread for when I want the scripts to run. The code looks like this.

Script 1

function Update(dt, owner)
   print("Script 1")
   pos = GetPosition(owner)
end

Script 2

function Update(dt, owner)
   print("Script 2")
end

GetPosition()

static int GetPosition(lua_State* L)
    {
        Core::Entity entity = lua_tonumber(L, 1);
        Core::TransformationComponent* tc = WGETC<Core::TransformationComponent>(entity);

        lua_newtable(L);

        for (int i = 0; i < 2; i++)
        {
            lua_pushnumber(L, tc->position[i]);
            lua_rawseti(L, -2, i);
        }

        return 1;
    }

How I create new lua threads (m_luaState is the global parent state to which I bind all my functions):

lua_State* LuaCore::CreateThread(std::string file)
    {
        lua_State* newState = lua_newthread(m_luaState);

        lua_newtable(newState); //new globals table
        lua_newtable(newState); //metatable

        lua_pushliteral(newState, "__index");
        lua_pushvalue(newState, LUA_GLOBALSINDEX); //original globals
        lua_settable(newState, -3);
        lua_setmetatable(newState, -2);
        lua_replace(newState, LUA_GLOBALSINDEX); //replace newState's globals

        luaL_dofile(newState, file.c_str());

        return newState;
    }

How each script is called:

            lua_State* ls = GetChildState(stateIndex)
            lua_pushstring(ls, functionName.c_str());
            lua_gettable(ls, LUA_GLOBALSINDEX);

            SimpleLuaCallData* slcd = (SimpleLuaCallData*)inData;

            lua_pushnumber(ls, slcd->dt);
            lua_pushnumber(ls, slcd->ownerID);

            lua_pcall(ls, 2, 0, 0);

            return nullptr;

If I remove the call to GetPosition from Script 1, the application runs without issue. Am I missing some kind of required clean-up or garbage collection problems? I'd like to try and avoid creating a new state for each entity, as that seems excessive and sharing globals via the core state is nice. lua_pcall doesn't produce any results. The application eventually stops running Script 1 and after a few more cycles it gets the access violation on

lua_gettable(ls, LUA_GLOBALSINDEX);

in the calling function.


texts:
I'm developing a game with quite a rich story. I'm not sure if I'll have enough  time or money to make a level for each part of this story.

Is there a common method among designer to manage this problem ? Should I write the entire story first and then cut some parts to fit it in my time/money budget ?


texts:
I have a question regarding declaring my inventory. I made it a string named inventory, with a constant number as its max value. The thing is, I want the user to use an item if he / she gains an item. The problem is, I do not know what syntax should I use to determine if the user has an item and use that item. Here's my code I just started:

so declaring the inventory:

    const int MAX_ITEMS = 15;
    string game_inventory [MAX_ITEMS];
    int itemnum = 0;

I have some items like potion, antidote, gems and others. I use the:

game_inventory[itemnum++] = "Potion"

to place items in my inventory. If I want to use the potion, IF I HAVE one, how can i make a function to check whether I have a potion or anything and use it?


texts: C# What is the advantage of using interfaces for simulating multiple inheritance?

texts:
Interfaces are a feature of C# that I've never quite been able to see the purpose of. I see them used all the time in professional code, but for the life of me I can't work out the reasoning.

My question here is specifically about interfaces to simulate multiple inheritance. In reading around the subject, I'll often come up on an example like this:

interface IAddition
{
    int add(int a, int b);
}

interface ISubtraction
{
    int sub(int a, int b);
}

class Calculation : IAddition, ISubtraction
{
    public int add(int a, int b)
    {
        return result1 = a + b;
    }

    public int sub(int a, int b)
    {
        return result1 = a - b;
    }
}

What I don't understand is - what benefit do the interfaces bring here? It looks to me like you could remove them completely, and the Calculation class would still work exactly the same. What am I missing here?

Any help would be appreciated - I've been looking for something to make interfaces 'click' in my head for quite a while now.

The reason I look for the solution to this is for making games. Multiple inheritance seems to be a good solution for making flexible game objects, but I've haven't quite got a proper grasp of it yet.


texts: Do GLSL 4.x subroutine variables cause any performance overhead?

texts:
There's not too much deep information about them on the web.

How are they implemented and how they work under the hood? I'd like to know that they cause any performance overhead or not, especially in the case of multiple subroutines to decide what's the best practice to create different versions of shaders: subroutines or separate shaders.

Any info or advice?


texts: Difference between WM_KEYDOWN and GetAsyncKeyState()

texts:
I am programming a simple Ping-Pong game in C++ but I don't know how to handle key presses. At first I intended to use WM_KEYDOWN, but I don't know how to track two pressed keys at once since the window processing function always gets only one wParam right? Basicaly I have two paddles on each side of the screen and when user presses W/S, left paddle moves, when Up/Down keys are pressed, right paddle moves. However when I press two keys at once only one paddle moves.

Another problem is that there is always a short pause after key is pressed - the paddle moves once in desired direction, then pauses and then continues to move. I have no idea why this happens. On the other hand when I use GetAsyncKeyState() like this:

if (GetAsyncKeyState('S') & 0x8000)
{
    PingPong.MoveLeftPaddleDown(hWnd);
}

everything works as intended - both paddles can move at the same time and there is no short pause on the beginning of movement. On the internet I read everywhere that I should use WM_KEYDOWN insead of GetAsyncKeyState() but how to configure it properly? Thank you


texts: Scene2d How to make it work for a Visual Novel

texts:
I kinda understand that you can use Scene2d for a Hud or stuff like that, I'm new to Java and so far I've done games that update in real time like let's say Flappy bird (simple games), so i wanted to try something different and now I'm kinda stuck, instead of having all the level be decided at the start of the game i want to instead have a forward and backwards button (Visual Novel) that lets me update the screen on each click, the problem is that i don't know how to do it in a clean way, is there a way to update the button on real time or any technique to have an entire "dialog level" scripted?
(sorry if this sounds confusing i don't know how to phrase it properly, if you have played or seen a visual novel you would understand what I'm talking about)


texts: Is SharpDX mature enough to adopt yet or should I just start using SlimDX right now?

texts:
I'm about to stop my game-project in XNA because from what I can gather it's development is coming to an end (and it's already behind current technology). Therefore, I need to adopt a new framework or API.

I have just spent 2 days looking at C++ and decided it's really not for me - however I do find the raw access to DirectX appealing. SharpDX sounds like a good place to start, but it has no documentation and no code comments. I feel like it's not quite ready for use.

I'm interested in the opinions of people that have used either or both of these frameworks, to help me decide for sure which one I should learn? Thanks for any advice.


texts:
(Although I'm sure this is a common problem I really don't know what to search for. Composition is the only thing I could come up with.)

I've read over and over that multiple inheritance and subclassing is really, really bad, especially for game entities. If I have three types of motions, five types of guns, and three types of armoring, I don't want to have to make 45 different classes to get all the possible combinations; I'm going to add a motion behavior, gun behavior, and armor behavior to a single generic object. That makes sense.

But how far do I take this?

I can have as many different types of behaviors as I can imagine: DamageBehavior, MotionBehavior, TargetableBehavior, etc. If I add a new class of behaviors then I need to update all the other classes that use them. But what happens when I have functionality that doesn't really fit into one class of behaviors? For example, my armor needs to be damageable but also updateable. And should I be able to have use more than one type of behavior on an entity at a time, such as two motion behaviors?

Can anyone offer any wisdom or point me in the direction of some useful articles?

Thanks!


texts: Java application chokes - when using MySQL

texts:
If I use localhost - XAMPP, my application runs without problems.
Once I try to use real MySQL databases: db4free.net, freedb.tech.
Applications begins to choke and freezing, resulting it is nearly impossible to use.
If I choose to use paid MySQL database, will it solve problem?
public static void scanningPlayers ()
{
    updatePlayers.setNode( GameGroups.finalRoot); // does'nt matter node.
    updatePlayers.setDuration(Duration.millis(1000));
    updatePlayers.play();
    updatePlayers.setOnFinished(evt ->
    {
        GameGroups.rootPlayers.getChildren().clear();

        try
        {
            Statement stmt      = Credentials.conn.createStatement();
            ResultSet users     = stmt.executeQuery("select id, name, avatar, Xpos, Ypos from users");

            while ( users.next() )
            {
                Label playerName            = Default.Label17Light  ( "" + users.getString("name"), users.getInt("Xpos"), users.getInt("Ypos") - 25 );
                ImageView hero;

                hero            = Default.ImageView( Dir.adventure + users.getString("avatar") + ".png", users.getInt("Xpos"), users.getInt("Ypos") );

                GameGroups.rootPlayers.getChildren().addAll ( playerName, hero );

                if ( users.getInt("id") == Variables.id )
                { //identify mysel, used for centering n door.
                    Variables.Xpos = users.getInt("Xpos");
                    Variables.Ypos = users.getInt("Ypos");
                    Variables.myAvatar = hero;

                    GameGroups.rootUniverse.setTranslateX ( -Variables.Xpos  + 550);
                    GameGroups.rootUniverse.setTranslateY ( -Variables.Ypos  + 362);
                }
            }
        } catch (SQLException e) {e.printStackTrace(); }

        updatePlayers.play();
    });
}


texts: Efficient per-frame constants in shaders

texts:
I have some variables that stay the same during the entire frame and will be used by a large number of the various shaders I use (several dozens). These include things such as the various transforms of the camera, light source data, etc.

The main options to provide this data to all the shaders (at least that I can think of) are:

Just give each shader uniforms for the data and set all uniforms manually when they're required
Use buffers, such as

Uniform Buffer Objects
Shader Storage Buffer Objects
Buffer Textures

Which of these options is generally the most performance efficient, and why?


texts: Unity editor stalling on second attempt to play

texts:
I am attempting to use a Tobii TX300 eye-tracker as an input device for Unity. This device is connected via LAN (TCP connection managed by Tobii SDK). The Tobii SDK has appropriate methods (I am writing in C#/mono) for opening and closing connections with the device.

I can 'play' my application once within the Unity editor and everything works as expected, but on the second attempt to 'play' the game, the editor stalls. The problem also occurs if I am currently playing the game in the editor, and then synchronize any code changes. I notice that this thread remains open:

mono.dll!mono_unity_socket_security_enabled_set+0x1e04 (there are usually at least 3-4 threads with the same name, but one always consumes a higher amount of cpu).

If I kill it manually using ProcessHacker then the Unity editor resumes normal operation.

The problem also occurs if I build the application into an executable. The game will play fine, but as soon as I attempt to exit then the application freezes, and I have to manually kill the process.

void Start ()
{
    Library.Init();
    eyeTracker = EyetrackerFactory.CreateEyetracker(SERVER, SERVER_PORT, SYNC_PORT, EventThreadingOptions.BackgroundThread);
    eyeTracker.StartTracking();
}

void OnApplicationQuit()
{
    eyeTracker.StopTracking();
    eyeTracker.Dispose();
}

Does anyone have any suggestions on why this thread is remaining open, or how to release resources within Unity scripts?


texts: Managing many draw calls for dynamic objects

texts:
We are developing a game (cross-platform) using Irrlicht. The game has many (around 200 - 500) dynamic objects flying around during the game. Most of these objects are static mesh and build from 20 - 50 unique Meshes.

We created seperate scenenodes for each object and referring its mesh instance. But the output was very much unexpected.

Menu screen: (150 tris - Just to show you the full speed rendering performance of 2 test computers)
a) NVidia Quadro FX 3800 with 1GB: 1600 FPS DirectX and 2600 FPS on OpenGL
b) Mac Mini with Geforce 9400M 256mb: 260 FPS in OpenGL

Now inside the game in a test level: (160 dynamic objects counting around 10K tris):
a) NVidia Quadro FX 3800 with 1GB: 45 FPS DirectX and 50 FPS on OpenGL
b) Mac Mini with Geforce 9400M 256mb: 45 FPS in OpenGL

Obviously we don't have the option of mesh batch rendering as most of the objects are dynamic. And the one big static terrain is already in single mesh buffer. To add more information, we use one 2048 png for texture for most of the dynamic objects. And our collision detection hardly and other calculations hardly make any impact on FPS. So we understood its the draw calls we make that eats up all FPS. Is there a way we can optimize the rendering, or are we missing something?


texts: Spell casting - How to optimize damage per second

texts:
Imagine we have a wizard that knows a few spells. Each spell has 3 attributes: Damage, cool down time, and a cast time. Pretty standard RPG stuff.

Cooldown time: the amount of time (t) it takes before being able to cast that spell again. A spell goes on "cooldown" the moment it begins casting.

Cast time: the amount of time (t) it takes to use a spell. While the wizard is casting something another spell cannot be cast and it cannot be canceled.

The question is: How would you maximize damage given different sets of spells?

It is easy to calculate the highest damage per cast time. But what about in situations where it is better to wait then to get "stuck" casting a low damage spell when a much higher one is available?

For example,

Fireball: 3000 damage, 3 second cast time, 6 second cool down.
Frostbolt: 20 damage, 4 second cast time, 4 second cool down.
Fireblast: 3 damage, 3 second cast time, 3 second cool down.

In this case your damage per second is higher if you chose to go for the lower DPCT spell (fireblast) instead of the frostbolt. So we must consider consequences of choosing a spell.

In the following example are cases of "over casting" and "waiting".


texts:
I'm building my very first game with XNA and i'm trying to get my sprite to run.
Everything is working fine for the first sprite.
E.g : if I go right(D) my sprite is looking right , if I go left(A) my sprite is looking left and if I don't touch anything my sprite is the default one.
Now what I want to do is if the sprite goes Right, i want to alternatively change sprites (left leg, right leg, left leg etc..) xCurrent is the current sprite drawn xRunRight is the first running Sprite and xRunRight1 is the one that have to exchange with xRunRight while running right.
This is what I have now :

    protected override void Update(GameTime gameTime)
    {
        float timer = 0f;
        float interval = 50f;
        bool frame1 = false ;
        bool frame2 = false;
        bool running = false;

        KeyboardState FaKeyboard = Keyboard.GetState();
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

            if ((FaKeyboard.IsKeyUp(Keys.A)) || (FaKeyboard.IsKeyUp(Keys.D)))
            {
                xCurrent = xDefault;
            }

            if (FaKeyboard.IsKeyDown(Keys.D))
            {

                timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                if (timer > interval)
                {
                    if (frame1)
                    {
                        xCurrent = xRunRight;
                        frame1 = false;
                    }
                    else
                    {
                        xCurrent = xRunRight1;
                        frame1 = true;

                    }
                }

                xPosition += xDeplacement;

            }

Any ideas...? I've been stuck on this for a while..
Thanks in advance and let me know if you need any other part from the code.


texts:
I looked at blendswap.com where there are models that I want to make walk along a wall in this level.
AFAIK I can take this file and sell it or did I misunderstand licensing?


texts: How to make UI Button to rotate an gameobject?

texts:
I'm trying to make a button to make a gameobject rotate and stay rotating in its own axis (Y) but I cannot make it work...

As far as I know it's very simple:

Create an empty gameobject (or whatever you want)
Make a script and attach it to the gameobject
Create public methods
Link the gameobject with the script attached to the button onClick event
Click the button and test the script

My problem is that I don't know how I'm wrong here are the scripts of my project

This first script is my attempt using keys, and it works like charm

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurntableRotation : MonoBehaviour
{
    public GameObject turntable;
    public float turnSpeed;
    public bool canRotate = false;

    void Start ()
    {
    }

    void Update ()
    {
        StartTurntableRotation();

        StopTurntableRotation();
    }

    public void StartTurntableRotation()
    {
        if (Input.GetKey(KeyCode.I))
            {
                canRotate = true;
            }

            if (canRotate)
            {
                turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
            }
    }

    public void StopTurntableRotation()
    {
        if (Input.GetKey(KeyCode.P))
        {
            canRotate = false;
        }

        if (!canRotate)
        {
            turntable.transform.Rotate(0,0,0);
        }
    }
}

This second script is my work in progress

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TurntableUIBtns : MonoBehaviour
{
    public GameObject turntable;
    public float turnSpeed;

        //This is my public method used by the button
    public void StartTurntableBtn()
    {

                //This is my attempt to write the code for the object to rotate
        turntable.transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
    }
}

As far as my knowledge goes, it is supposed to work, but I have to click every time to rotate my object, my goal is to click the button and make the object rotate and stay rotating


texts: How should I go about randomizing levels in a "runner" game?

texts:
I'm working on a runner type of game (basically it's a never ending run through hordes of enemies and platforms and whatnot). 2d platformer view.

Should I random a bit of map every now and then? Few screens or 30 screens? And what about platforms and ground to make the whole thing "doable". Can I find any resources on that subject?


texts: glsl uniform int as index of const array

texts:
I have a const array that define a few materials for directionnal light. I'd like to change the material using an uniform int as index of that array. Doing that leads to severe framerate drop.

I know that this could be fixed by just keeping the array in the cpu and send the material as uniform. But why does this not lead to framerate drop and the other do?

It seems that even with 2 elements in my array I have framerate drops. But accessing the array with a constant doesn't make me lag ( I presume glsl drivers optimize this by replacing the line with the correct element in the array ).

This is my shader :

struct Material
{
    vec3 ambiant, diffuse, specular;
    float shininess;
};

const Material materials[] = Material[]
(
    Material( vec3( 0.05375, 0.05, 0.06625 ), vec3( 0.18275, 0.17, 0.22525 ), vec3(  0.332741, 0.328634, 0.346435 ), 0.3 * 128 ),
    Material( vec3( 0.1, 0.18725, 0.1745 ), vec3( 0.396, 0.74151, 0.69102 ), vec3( 0.297254, 0.30829, 0.306678 ), 0.1 * 128 ),
    Material( vec3( 0.25, 0.25, 0.25 ), vec3( 0.4, 0.4, 0.4 ), vec3( 0.774597, 0.774597, 0.774597 ), 0.6 ),
    Material( vec3( 0.19125, 0.0735, 0.0225 ), vec3( 0.7038, 0.27048, 0.0828 ), vec3( 0.256777, 0.137622, 0.086014 ), 0.1 * 128 ),
    Material( vec3( 0.24725, 0.1995, 0.0745 ), vec3( 0.75164, 0.60648, 0.22648 ), vec3( 0.628281, 0.555802, 0.366065 ), 0.4 * 128 ),
    Material( vec3( 0.0, 0.0, 0.0 ), vec3( 0.5, 0.5, 0.0 ), vec3( 0.60, 0.60, 0.50 ), 0.25 * 128 ),
    Material( vec3( 0.05, 0.0, 0.0 ), vec3( 0.5, 0.4, 0.4 ), vec3( 0.7, 0.04, 0.04 ), 0.078125 * 128 )
);

void main()
{
    Material mat = materials[ index ];

    vec3 lightColor = vec3( 1.0, 1.0, 1.0 );

    float diffuseFactor = max( dot( normalize( Normal ), lightPos ), 0.0 );

    vec3 reflectedRay = reflect( -lightPos, normalize( Normal ) );
    float specularFactor = pow( max( dot( reflectedRay, normalize( cameraPos - Position ) ), 0.0 ), mat.shininess );

    vec3 ambiantColor = lightColor * mat.ambiant;
    vec3 diffuseColor = diffuseFactor * lightColor * mat.diffuse;
    vec3 specularColor = specularFactor * lightColor * mat.specular;

    color = vec4( ambiantColor + diffuseColor + specularColor, 1.0f );
}


texts: Can GMod/SFM models be converted to Unity GameObjects?

texts:
Someone made a suite of GMod/SFM models available for free for people making games and videos in GMod and SFM. These are of type .dmx, .dx80.vtx, .dx90.vtx, .mdl, .phy, .sw.vtx, .vvd, .vmt, and .vtf. I don't use GMod or SFM, so I don't know what these are, thus making it hard for me to manually convert them. Is there any way to change these into files Unity can recognize and use?

I'd like to have an easy step from converting them, but I would also accept instructions on how to export them to generic mesh/skeleton/texture files, and then how to import and combine these in Unity.


texts:
I'm trying to use (un)packHalf2x16, without success so far. I'm drawing with:

glVertexAttribIPointer(0, 2, GL_UNSIGNED_INT, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glDrawArrays(GL_POINTS, 0, n_points);
glDisableVertexAttribArray(0);

and on the shader

#version 330 core
#extension GL_ARB_shading_language_packing : require
in uvec2 A0;
// (...)
vec4 t = vec4(unpackHalf2x16(A0.x), unpackHalf2x16(A0.y));

But nothing gets drawn. I'm pretty sure buffer's content is right, and if I use vec4 t = vec4(0); I can see it's working properly.
How is this packing / unpacking thing supposed to work? I can't find any example.


texts: Free vs. Paid: Picking a Financial Model

texts:
I finally embarked upon my first "paid" game. What this means is that I will incorporate some sort of monetization strategy in my game. This may mean making the app pay-to-download, making it "freemium" with paid content, or something else.

Having never done something like this, I'm at a complete loss as to how to figure out what I should do. I know a couple of models (pay to download, freemium, etc.) and I can brainstorm some ideas. But how do I figure out what strategy to use?

Perhaps there's some body of research on this? (I recall reading that MMOs popular in Korea use a model where cosmetic changes only are pay-to-buy; everything else is free).


texts: How do I set up a dedicated server for my multiplayer Unity game?

texts:
I've made a multiplayer game with Unity and Mirror networking, and it all works perfectly when just running it on my own computer. However, I am trying to host on a dedicated server so that I can put the project on my portfolio and not have to worry about whether players can log in and test/play the game or not.
I tried a AWS Free server and I see that the Tanks example from Mirror is working just fine (although laggy), but my own project doesn't. I think this has something to do with the RAM limit of the free server but I'm not sure. I can see the task manager going up to 95% memory usage. When I remove some particle effects and geometry and enemies, it works.
I'm not sure if this is my code that is so cloggy or the server or both. In any case I would need a solution for this but I don't know what my options are.
Would be great if anyone can point me in the right direction. Thanks!


texts: Unable to Merge Android manifest error is showing up

texts:
I used Google Admob to put ads in my game but as soon as I hit build and run this error showed up I used a Github file and imported into my unity project, I will link it right here

https://github.com/unity-plugins/Unity-Admob.

CommandInvokationFailure: Unable to merge android manifests. See the Console for more details.
C:\Program Files (x86)\Java\jdk1.8.0_101\bin\java.exe -Xmx1024M -Dcom.android.sdkmanager.toolsdir="C:/Users/jayso/AppData/Local/Android/android-sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -
stderr[
Error: [Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-ads-10.2.0\AndroidManifest.xml:2] Main manifest has  but library uses minSdkVersion='14'
Error: [Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-ads-lite-10.2.0\AndroidManifest.xml:7] Main manifest has  but library uses minSdkVersion='14'
Error: [Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-base-10.2.0\AndroidManifest.xml:2] Main manifest has  but library uses minSdkVersion='14'
Error: [Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-basement-10.2.0\AndroidManifest.xml:2] Main manifest has  but library uses minSdkVersion='14'
Error: [Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-gass-10.2.0\AndroidManifest.xml:2] Main manifest has  but library uses minSdkVersion='14'
Error: [Temp\StagingArea\AndroidManifest-main.xml:21, C:\Users\jayso\OneDrive\Documents\Tap Happy\Temp\StagingArea\android-libraries\play-services-tasks-10.2.0\AndroidManifest.xml:2] Main manifest has  but library uses minSdkVersion='14'
]
stdout[
]
exit code: 1
UnityEditor.Android.Command.Run (System.Diagnostics.ProcessStartInfo psi, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandInternal (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.Android.AndroidSDKTools.RunCommandSafe (System.String javaExe, System.String sdkToolsDir, System.String[] sdkToolCommand, Int32 memoryMB, System.String workingdir, UnityEditor.Android.WaitingForProcessToExit waitingForProcessToExit, System.String errorMsg)
UnityEditor.BuildPlayerWindow:BuildPlayerAndRun()


texts: Dynamically editing a movieclip at runtime

texts: I am trying to make a flash game(actionScript-3 if it matters) to test what I learned so far. And, in the game, I want to make the character(a robot?) customizable. The first solution I found was to edit the character movieclip directy. Is it possible to edit a movieclip at runtime? If yes, how?


texts:
I am trying to learn DX10 by following this tutorial. However, my shader won't compile. Below is the detailed error message.

Build started 9/10/2012 10:22:46 PM.
     1>Project "D:\code\dx\Engine\Engine\Engine.vcxproj" on node 2 (Build target(s)).
         C:\Program Files (x86)\Windows Kits\8.0\bin\x86\fxc.exe /nologo /E"main" /Fo "D:\code\dx\Engine\Debug\color.cso" /Od /Zi color.fx
     1>FXC : error X3501: 'main': entrypoint not found

         compilation failed; no code produced
     1>Done Building Project "D:\code\dx\Engine\Engine\Engine.vcxproj" (Build target(s)) -- FAILED.

Build FAILED.

Time Elapsed 00:00:00.05

I can easily compile the downloaded code, but I want to know how to fix this error myself.

My color.fx looks like this

  ////////////////////////////////////////////////////////////////////////////////
  // Filename: color.fx
  ////////////////////////////////////////////////////////////////////////////////

  /////////////
  // GLOBALS //
  /////////////
  matrix worldMatrix;
  matrix viewMatrix;
  matrix projectionMatrix;

  //////////////
  // TYPEDEFS //
  //////////////
  struct VertexInputType
  {
      float4 position : POSITION;
      float4 color : COLOR;
  };

  struct PixelInputType
  {
      float4 position : SV_POSITION;
      float4 color : COLOR;
  };

  ////////////////////////////////////////////////////////////////////////////////
  // Vertex Shader
  ////////////////////////////////////////////////////////////////////////////////
  PixelInputType ColorVertexShader(VertexInputType input)
  {
      PixelInputType output;

     // Change the position vector to be 4 units for proper matrix calculations.
      input.position.w = 1.0f;

     // Calculate the position of the vertex against the world, view, and projection matrices.
      output.position = mul(input.position, worldMatrix);
      output.position = mul(output.position, viewMatrix);
      output.position = mul(output.position, projectionMatrix);

     // Store the input color for the pixel shader to use.
      output.color = input.color;

     return output;
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Pixel Shader
  ////////////////////////////////////////////////////////////////////////////////
  float4 ColorPixelShader(PixelInputType input) : SV_Target
  {
      return input.color;
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Technique
  ////////////////////////////////////////////////////////////////////////////////
  technique10 ColorTechnique
  {
      pass pass0
      {
          SetVertexShader(CompileShader(vs_4_0, ColorVertexShader()));
          SetPixelShader(CompileShader(ps_4_0, ColorPixelShader()));
          SetGeometryShader(NULL);
      }
  }


texts: GLSL: Issue replacing ternary operator with mix

texts:
I was expecting these two code snippets to do the same thing:

return  vec3(  1.0-b.r>=a.r ? 0.0 : 1.0-((1.0-b.r)/a.r),
               1.0-b.g>=a.g ? 0.0 : 1.0-((1.0-b.g)/a.g),
               1.0-b.b>=a.b ? 0.0 : 1.0-((1.0-b.b)/a.b)  );

and

return mix( ONE3 - ((ONE3-b)/a), ZERO3, vec3(greaterThanEqual(ONE3-b, a)) );
       // ONE3=vec3(1.0,1.0,1.0); ZERO3=vec3(0.0,0.0,0.0);

For some reason, they have different outputs. Do you know why? (a can have zeros sometimes)


texts:
Is it possible to calculate the best possible placements for settlements in Catan without using an ML algorithm?

While it is trivial to simply add up the numbers surrounding the settlement (highest point location), I'm looking to build a deeper analysis of the settlement locations. For example, if the highest point location is around a sheep-sheep-sheep, it might be better to go to a lower point location for better resource access. It could also weight for complementary resources, blocking other players from resources, and being closer to ports.

It seems feasible to program arithmetically, yet some friends said this is an ML problem. If it is ML, how would one go about training, as the gameboard changes every game?

Edit: Catan is fairly complex, but involves a setup of placing hexagonal "tiles" randomly to make the board (example board below) . One can then, in turn with the other players, place 2 settlements on the board at corners. Settlements cannot be placed on corners directly next to each other, giving you the ability to deny spots to others. Settlements give you the ability to get the 3 resources around them. One needs certain resources to do certain things, but generally even-ish balance of resources through the game. You also want resources with number chips closer to 7, as you only get the resource if the 2 die rolled every turn land on that number. After the 2 initial settlements, you can build roads out and build new settlements. If you have a settlement on a port, you can also trade according to that port's trade type.

see this video for a tutorial on Catan


texts: Simulated Economic Factors Based on Supply and Demand in MMO Resource Trading Game

texts:
I'm working on a gam (naturally), and the primary activity for the player is to buy and sell commodities at various marketplaces.

Each commodity has the following properties:

Base Price: if all things were otherwise equal, this would be the measure of value for the commodity
Supply Factor: when a player sells one unit of this commodity in a market, the "supply" goes up by this factor
Demand Factor: when a player purchases one unit of this commodity in a market, the "demand" goes up by this factor.

Within each market, the commodities are given the following local properties:
Local Supply
Local Demand

To keep things "simple", I have these values generated randomly with the equivalent of a 3d6, so Supply and Demand can be anywhere from 3-18.

The price for one unit of a commodity in a particular market is calculated like so:

Price = BasePrice * (LocalDemand+DemandFactor*UnitsDemanded) / (LocalSupply+SupplyFactor*UnitsSupplied)

In this way, player purchases will drive the price up, and player sales will drive the price down.

Now comes the problem, and I'll use a concrete example as it is not entirely obvious from just looking at the formula.

We have commodity X with a base price of 100, and local demand and local supply both of 10, and a supply and demand factor each of 1.

So, desiring to purchase a single unit, I calculate the price:

Price = 100 * (10+1*0) / (10+1*0) = 100

And I purchase the unit, which drives up the price to:

Price = 100 * (10+1*1) / (10+1*0) = 110

And if the player then sells the commodity at that price, he immediately profits 10.

This is no good.

So, my first pass at this solution is to calculate the price based on what the supply or demand WILL BE after the purchase is over, which works after a fashion, but consider that in the example above, the purchase of 1 unit will be 110, whereas the purchase of 10 units will have a unit price of:

(100 * (10+1*10) / (10+1*0)) = 200 (total of 2000 to buy 10 units)

So, naturally this is unfair, and so the player would get the best price for purchasing one unit at a time.

And I don't want the player to have to do that, so I want to calculate the price one unit at a time.

This in itself is relatively easy, just loop through the units I want to purchase, and add it up.

Unfortunately, it doesn't exactly take care of the fractional units.

I might not have mentioned that you can own fractional units of commodities. You can.

Another thing to compound the issue is that the "currency" is simply another commodity, which can itself have supply, demand, supply factor, demand factor, sales, purchases, and so on.

So purchasing is a two step problem.

First, for a particular number of units of a commodity, determine the "value" of them in a way that ensure that buying and then immediately selling is a losing proposition.

Second, for a particular "value", determine the number of units that would need to be "sold" in order to make up that value.

Another wrinkle: it should not be advantageous to purchase fractional units.  The price for buying half a unit, and then buying another half a unit should not be better or worse than buying one whole unit at one time.


texts:
I am using SharpDX, a C# wrapper over DirectX 11 to render terrain.  While I am able to render terrain correctly, I noticed that moving around creates a lot of visual noise and makes the texture of the ground very grainy.  I have attached a picture of how the texture looks on the terrain. (Make sure to make full screen for clarity)

Here is the dirt texture I am using:

Here is the dirt texture normal map:

I thought I set up the mip maps appropriately in this code (note that filename is just the path to the terrain bitmap I showed above):

public bool Initialize(SharpDX.Direct3D11.Device device, string fileName)
{
  try
  {
    using (var texture = LoadFromFile(device, new SharpDX.WIC.ImagingFactory(), fileName))
    {
      ShaderResourceViewDescription srvDesc = new ShaderResourceViewDescription()
      {
        Format = texture.Description.Format,
        Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
      };
      srvDesc.Texture2D.MostDetailedMip = 0;
      srvDesc.Texture2D.MipLevels = -1;

      TextureResource = new ShaderResourceView(device, texture, srvDesc);
      device.ImmediateContext.GenerateMips(TextureResource);
    }
    // TextureResource = ShaderResourceView.FromFile(device, fileName);
    return true;
  }
  catch
  {
    return false;
  }
}

public Texture2D LoadFromFile(SharpDX.Direct3D11.Device device, ImagingFactory factory, string fileName)
{
  using (var bs = LoadBitmap(factory, fileName))
    return CreateTexture2DFromBitmapSource(device, bs);
}

public BitmapSource LoadBitmap(ImagingFactory factory, string filename)
{
  var bitmapDecoder = new SharpDX.WIC.BitmapDecoder(
      factory,
      filename,
      SharpDX.WIC.DecodeOptions.CacheOnDemand
      );

  var result = new SharpDX.WIC.FormatConverter(factory);

  result.Initialize(
      bitmapDecoder.GetFrame(0),
      SharpDX.WIC.PixelFormat.Format32bppPRGBA,
      SharpDX.WIC.BitmapDitherType.None,
      null,
      0.0,
      SharpDX.WIC.BitmapPaletteType.Custom);

  return result;
}

 public Texture2D CreateTexture2DFromBitmapSource(SharpDX.Direct3D11.Device device, BitmapSource bitmapSource)
{
  // Allocate DataStream to receive the WIC image pixels
  int stride = bitmapSource.Size.Width * 4;
  using (var buffer = new SharpDX.DataStream(bitmapSource.Size.Height * stride, true, true))
  {
    // Copy the content of the WIC to the buffer
    bitmapSource.CopyPixels(stride, buffer);
    return new SharpDX.Direct3D11.Texture2D(device, new SharpDX.Direct3D11.Texture2DDescription()
    {
      Width = bitmapSource.Size.Width,
      Height = bitmapSource.Size.Height,
      ArraySize = 1,
      BindFlags = SharpDX.Direct3D11.BindFlags.ShaderResource | BindFlags.RenderTarget,
      Usage = SharpDX.Direct3D11.ResourceUsage.Default,
      CpuAccessFlags = SharpDX.Direct3D11.CpuAccessFlags.None,
      Format = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
      MipLevels = 1,
      OptionFlags = ResourceOptionFlags.GenerateMipMaps, // ResourceOptionFlags.GenerateMipMap
      SampleDescription = new SharpDX.DXGI.SampleDescription(1, 0),
    }, new SharpDX.DataRectangle(buffer.DataPointer, stride));
  }
}

Here is my samplerstate code:

SamplerStateDescription samplerDesc = new SamplerStateDescription()
            {
                Filter = Filter.MinMagMipLinear,
                AddressU = TextureAddressMode.Clamp,
                AddressV = TextureAddressMode.Clamp,
                AddressW = TextureAddressMode.Clamp,
                MipLodBias = 0,
                MaximumAnisotropy = 1,
                ComparisonFunction = Comparison.Always,
                BorderColor = new Color4(0, 0, 0, 0),  // Black Border.
                MinimumLod = 0,
                MaximumLod = float.MaxValue
            };
            SamplerState = new SamplerState(device, samplerDesc);

Is there anything wrong here?


texts: How to place a camera so that it always fits a plane?

texts:
I have a plane that can get its scale changed during the game, and I want to make the camera view it completely every time the plane has its scale changed. The only camera is set to perspective projection.

I found this page which tells me how to resize the plane (I do not understand the unity of measure used there) to be viewed by the camera, and I want the reverse.

I found something similar here.

I also found other not-very-relevant answers by googling "unity camera fits a plane", "unity move camera to show an object" (one of the results is this), "unity field of view to fit an object" (one of the results is this).

I think I found the answer here, but it is hard for me to do the maths right now. I also found an answer here but I wish that someone explained me the mathematics (also, I do not know how to get the bounds).

My relevant previous question with the same situation is here. There is a link to download a sample project, and a few screenshots.

Thank you.


texts: Collision with supposedly aligned box-colliders

texts:
I am quite new to game development, and I am trying to create a top-down game with 2D sprites, but with a 3D feel to it. I managed to do so with the 2D engine by setting Transparency Sort Mode to Custom Axis with the axis values set to (X=0,Y=1,Z=0). I then moved the pivot of GameObjects to bottom-center and used the pivot as sorting point for the sprites. I am now trying to create the environment, but my character 'clips' against the Box Colliders, even though I did all I could think of to align them (same pivot coordinates, same collider offset and size). See the attached GIF for an example:

I think that the cause is mentioned here, but there are no solutions mentioned there. My two solutions:

Remove the colliders, group the objects in a parent object, and add the collider there. But then I would get the same issue if I place two of those instances next to each other.
I am still pondering to drop this approach altogether and try the same in the 3D engine, but with a fixed camera angle. I lack experience to estimate if that would be a better approach, so if someone thinks that approach would be better suited to this game style, I am happy to hear it.

Can anyone give me advice on this issue, or point me towards resources that might be useful?
Thanks in advance,
Florian

Some pictures of the settings I used:


texts:
I'm working on a Flash game after many, many years. I'm trying to figure out size to make my application run (eg. 600x800). Because it's a tall (not wide) game, I'm confused.

I know about (and love) the Steam hardware stats. However, for Flash gaming, I have two nit-picks with their survey sample:

1) Caters to more hardcore gamers with better hardware (overall)
2) Captures only a subset of Flash gamers. Doesn't capture people who play at school, work, etc. or not netbooks and lighter machines.

Are there any sort of statistics I can use to determine which size to use? Ideally, I would like to know something like:

800x600 will fit 94% of users screens
1024x768 will fit 74% of users screens
1200x960 will fit 53% of users screens
etc.


texts: Too many objects to update in db too often

texts:
We are creating a RTS mobile game and we face some problem dealing with updating a lot of object in db too often.

Our game is a RTS in which players can attack enemies cities an take them.
The world is procedural and potentially infinite, when players spawn we extend the map if needed (no city left).
Our map is reset every month.
Each city hold an army and produce an amount of army based on the city level.
We also have some items that the player can equip and unequip. Those items may give some army production bonus.

At the biginning most of players had around 30-50 cities. But since the player number increased some players now have over 1000 cities.

Our data structure look like this (mongodb)

City:
- id (ObjectId)
- location [x(int), y(int)]
- level (int)
- armyAmount (double)
- lastArmyUpdate (Date)
- armyProductionMultiplier (double)

Player:
- id (ObjectId)
- Name (string)
- Items [key (int), equiped(bool)]
- Cities [cityId (ObjectId)]

When a city is attacked we refresh the army based on the last update and the city production.

army = oldArmy + cityProduction*armyProductionMultiplier*TimeSinceLastUpdate

It works well as we only update the value when needed.

But when players equip an item that give them army production bonus we need to update the multiplier on each city the player own and to update the army amount considering the old multiplier before applying the new one.
If the player only change his item once per day it's ok but if he swap  every minutes it will make a lot of database query and waste a lot of cpu time.

We could set a timer between items swap but it would be frustrating for the player.

QUESTION: Is there a db pattern or a better way to reduce the cost of the item swapping.

Thank you!


texts: How to correct mouse position to world position in xna/monogame

texts:
I'm making a small game where the player shoots projectiles by clicking the mouse.  Everything worked fine before adding in a camera.  Now the position of the new projectiles is always off.
shoot code:
    if (mouseState.LeftButton == ButtonState.Pressed)
        {
            Vector2 mousePos = new Vector2(mx, my);
            Vector2 worldPosition = Vector2.Transform(mousePos,
            Matrix.Invert(game.camera.transform));

            Shoot(new Vector2(mx, my), new Vector2(pos.X + 8 * scale.X, pos.Y + 8 * scale.Y),
            gameTime);
            buttonTimer--;
        }

Camera code:
    public class Camera
    {
    Handler handler;

    public Matrix transform { get; private set; }

    public Camera (Handler handler)
    {
        this.handler = handler;
    }

    public void Update (GameTime gameTime)
    {
        foreach (Player p in handler.players)
            Follow(p);
    }

    public void Follow(Player target)
    {
        var offset = Matrix.CreateTranslation(1200 / 2, 800 / 2, 0);

        var position = transform = Matrix.CreateTranslation(
            -target.pos.X - ((16 * target.scale.X) / 2),
            -target.pos.Y - ((16 * target.scale.Y) / 2),
            0);

        transform = position * offset;
    }
}

Bullet code:
    public class Projectile
{
    public bool isActive = true;

    Game1 game;
    Handler handler;
    Spritesheet ss;

    public Vector2 pos;
    public Vector2 scale;

    int type;

    public Vector2 vel;
    public Vector2 direction;
    public Vector2 origin;

    long startTime = 0;

    float speed = 14;

    int particleTimer = 0;

    Rectangle Bounds;

    public Projectile(Vector2 pos, Vector2 scale, int type, Game1 game, Handler handler)
    {
        this.pos = pos;
        this.scale = scale;
        this.type = type;
        this.game = game;
        this.handler = handler;

        this.ss = game.bullet_ss;

        origin = pos;
    }

    public void LoadContent(ContentManager content)
    {

    }

    public void Update(GameTime gameTime)
    {
        pos += direction * speed;
        CreateParticles();

        Collision();

        Bounds = new Rectangle((int)pos.X, (int)pos.Y, (int)(8 * scale.X), (int)(8 * scale.Y));
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(ss.frames[type, 0], pos, null, null, null, 0, scale);
    }

    private void Collision()
    {
        if (type == 0)
        {
            foreach (Platform p in handler.platforms)
            {
                if (this.Bounds.Intersects(p.Bounds)) isActive = false;
            }
        }
    }

    private void CreateParticles()
    {
        if (particleTimer > 2)
        {
            for (int i = 0; i < 3; i++)
            {
                Vector2 position = new Vector2(handler.rand.Next(8) * scale.X, handler.rand.Next(8) *
                scale.Y);
                Vector2 v = new Vector2(handler.rand.Next(8), handler.rand.Next(8));
                Particle p = new Particle(position + pos, v, new Vector2(4, 4), 0, game, handler);
                handler.particles.Add(p);
            }

            particleTimer = 0;
        }
        particleTimer++;
    }

What fixes can I implement so that the projectiles are created in the correct positon?


texts: What technology does the iPhone game "Zombie Highway" use?

texts:
Does anyone know anything about the technology behind the "Zombie Highway" iPhone game?

What 3D engine does it use, especially what kind of tools did they use for the UI animations, transitions, etc.?

Also, when you go to the settings screen, they are using the native iPhone keyboard and controls. Do you think that's all UIKit overlaid on top?

It looks brilliant!


texts: How to initialize once for all a static field of a custom editor in unity

texts:
I have a custom editor wich has a static field.

Suppose you have a static field of type MyObject:

public class myEditor : Editor {

...

private static MyObject myObj;

...
}

I'd like to initialize the field myObj directly on the same line of the declaration, but in this way I get a TypeInitializationException.

I could initialize  the field myObj in the method OnEnable, but in this way I have to use an if statement like the following:

if ( myObj == null )
    myObj = new MyObject();

Is there a way to initialize myObj once for all without using if statement?


texts: How to send multiple MVP matrices to a vertex shader in OpenGL ES 2.0

texts:
I'm working my way through optimizing the rendering of sprites in a 2D game using OpenGL ES and I've hit the limit of my knowledge when it comes to GLSL and vertex shaders.

I have two large float buffers containing my vertex coordinates and texture coordinates (eventually this will be one buffer) for multiple sprites in order to perform a single glDrawArrays call.  This works but I've hit a snag when it comes to passing the transformation matrix into the vertex shader.

My shader code is:

uniform mat4 u_MVPMatrix;
attribute vec4 a_Position;
attribute vec2 a_TexCoordinate;
varying vec2 v_TexCoordinate;

void main()
{
    v_TexCoordinate = a_TexCoordinate;
    gl_Position = u_MVPMatrix * a_Position;
}

In Java (Android) I am using a FloatBuffer to store the vertex/texture data and this is provided to the shader like so:

mGlEs20.glVertexAttribPointer(mVertexHandle, Globals.GL_POSITION_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mVertexCoordinates);
mGlEs20.glVertexAttribPointer(mTextureCoordinateHandle, Globals.GL_TEXTURE_VERTEX_COUNT, GLES20.GL_FLOAT, false, 0, mTextureCoordinates);

(The Globals.GL_POSITION_VERTEX_COUNT etc are just integers with the value of 2 right now)

And I'm passing the MVP (Model/View/Projection) matrix buffer like this:

GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mModelCoordinates);

(mModelCoordinates is a FloatBuffer containing 16-float sequences representing the MVP matrix for each sprite)

This renders my scene but all the sprites share the same transformation, so it's obviously only picking the first 16 elements from the buffer which makes sense since I am passing in "1" as the second parameter.  The documentation for this method says:

  "This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices."

So I tried modifying the shader with a fixed size array large enough to accomodate most of my scenarios:

uniform mat4 u_MVPMatrix[1000];

But this lead to an error in the shader:

  cannot convert from 'uniform array of 4X4 matrix of float' to 'Position 4-component vector of float'

This just seems wrong anyway as it's not clear to me how the shader would know when to transition to the next matrix anyway.

Anyone have an idea how I can get my shader to pick up a different MVP matrix (i.e. the NEXT 16 floats) from my MVP buffer for every 4 vertices it encounters?  (I am using GL_TRIANGLE_STRIP so each sprite has 4 vertices).

Thanks!


texts: Is Frustum Culling and Occlusion Culling used together, or separately?

texts:
I am taking a 3D game programming course and my professor provided the class with already-implemented graphics code with OpenGL. The graphics uses frustum culling to remove primitives outside the view of the camera. I did some stress testing by spawning 1000s of boxes and when all boxes are in the view of camera, the FPS drops significantly (from 60FPS to 10FPS).

I have several questions about graphics clipping:

Is Frustum Culling (FC) always implemented in every graphics engine?
I've read about Occlusion Culling (OC), where objects occluded behind other objects aren't rendered. Does this replace FC or are they used together?
Is OC more difficult to implement and therefore FC is the default clipping technique? I'm assuming implementing OC would increase the performance of my "game" since not all 1000s boxes would be rendered.

Any information is appreciated. Thanks!


texts: How do I change iTween values at runtime?

texts:
I am trying to figure out how to run and change the speed of rotation on an iTween path at runtime. I'm trying to code it in Unity5 in C#. I have to rotate a few objects on an iTween path which I have created and I have to manage the speeds of the objects at runtime as they change.

My problem is that:
If I write the code in start method then it runs once within the whole game. How can I use this script in Update method so I can manage the speeds at the run time?


texts:
I have a cube as my model and want to map a texture on every side of the cube. I have been searching for a while and most answers suggest using 3D max or using VertexPositionTextures.

I am not allowed to use any moddeling program, I have to use XNA, so that is not an option.
For VertexPositionTextures you have to provide a Vector3 and a vector2 containing the position and the some area of your texture. But then, why would I use a model if I provide the position myself? Do I get this wrong maybe?

I tried to add the texture to my effect with effect.texure = ... but I can't specify what to map. It just puts the texture on my model.

So how can I map a texture to my model and specify what and where to map?


texts:
I'm trying to capture the performance of the GPU, CPU, FPS and memory usage on a program I'm currently working with and want to avoid having to write my own performance capture stuff. Does anyone know of a good program/programs that can do 1 or more of the above?

Ideally something that is simple to use. I've googled a few, but getting them to work has been a right pain. The couple that I've tried out have given me my entire systems performance, as opposed to just my running program.

Any help would be appreciated. I'm currently using DirectX 9 and C++ for my program.


texts: Is a multiplayer game in JavaScript a bad idea?

texts:
What are the possible downsides to using (client side) JavaScript when creating a multiplayer game?

Game description: It's an MMORPG/RTS. That means players actively contribute to structures in the world and create much of the content themselves.


texts:
I have an object on my screen which is presented rotated and panned,
But i have 2 problems regarding the z axis rotations. It's a bit tricky to explain so i uploaded 2 videos to describe each problem.

1) Reverse rotation : After rotating the object around the x axis, the z rotations are being reversed and not as it should be.

2) Wrong Z axis rotation : Again, After rotating the object around the x axis, i'm trying to rotate the object around the z axis and the rotation results in a different axis rotations.

I do believe the video's describe the problems well.

EDIT: Second attempt

As kindly explained by the user @Fault, i understood the problems i was facing with.
So i tried to solve those by just rotating the projection matrix around the z axis, which seemed to be working, but it doesn't.

Since i am rotating the model's axis, I get this problem (video). the issue appears in the 23'd seconds, while i'm demonstrating how it works.
As can been seen, when the z rotation causes a wrong x and y rotations.

I do understand that i must likely have to move these rotations to world view and not model view, the thing is i'm not really sure how to do that.

Here is the relevant code:

Render function:

{
...

    CC3GLMatrix *projection = [CC3GLMatrix matrix];
    float h = 4.0f * self.frame.size.height / self.frame.size.width;
    [projection populateFromFrustumLeft:-2 andRight:2 andBottom:-h/2 andTop:h/2 andNear:4 andFar:100];
    [projection rotateByZ:zRotationEnd];
    glUniformMatrix4fv(_projectionUniform, 1, 0, projection.glMatrix);

    [modelView populateFromTranslation:_currentPan];
    [modelView rotateBy:_currentRotation];

    glUniformMatrix4fv(_modelViewUniform, 1, 0, modelView.glMatrix);
...
}

X and Y rotations:

- (void) rotateAroundX:(float) x andY:(float) y newRotate:(BOOL) isNewRotate
{
    if (isNewRotate) {
        rotationStart = CC3VectorMake(0.0, 0.0, 0.0);
    }

    int rotationDirection = ceil(zRotationEnd/90);
    if (rotationDirection % 4 == 2 || rotationDirection % 4 == 3) {
        rotationEnd.x = rotationEnd.x - (x-rotationStart.x);
        rotationEnd.y = rotationEnd.y - (y-rotationStart.y);
    } else {
        rotationEnd.x = rotationEnd.x + (x-rotationStart.x);
        rotationEnd.y = rotationEnd.y + (y-rotationStart.y);
    }

    rotationStart.x = x;
    rotationStart.y = y;
    _currentRotation = CC3VectorMake(rotationEnd.y, rotationEnd.x, 0);
    NSLog(@"Current x is: %f y is: %f z is: %f",_currentRotation.x,_currentRotation.y,zRotationEnd);

}

Z rotations:

- (void) rotateAroundZ:(float) z newRotate:(BOOL) isNewRotate
{
    if (isNewRotate) {
        zRotationStart = 0;
    }
    zRotationEnd = zRotationEnd - (z - zRotationStart);
    zRotationStart = z;
}

And the vertex shader:

attribute vec4 Position;
attribute vec4 SourceColor;

varying vec4 DestinationColor;

uniform mat4 Projection;
uniform mat4 Modelview;

attribute vec2 TexCoordIn;
varying vec2 TexCoordOut;

void main(void) {
    DestinationColor = SourceColor;
    gl_Position = Projection * Modelview * Position;
    TexCoordOut = TexCoordIn;
}

I would really like to get this right, so any help will be appreciated.

Cheers!


texts: Attaching scripts which trigger on specified events to objects

texts:
I'm new to Unity and C#. For concreteness, I'll phrase the question in terms of building a TCG like Magic: the Gathering or Hearhtstone, although the method seems of more general utility.
Suppose we wish to create cards that have special properties, such as: "when played, does [a thing]", or "Immunity to fire". Having created a card class, here is the pseudo-code that I would like to write, when initializing the 'library' of cards:
Card testCard = new Card( /*generic arguments here like HP, etc*/);

testCard.abilities = [fireImmunity, drawCardOnPlay, ...];

Where I would have defined the abilities fireImmunity, drawCardOnPlay, and all others in some convenient location. Of course, I could manually define these abilities on each card, but that seems like a short route to insanity: many cards will share the abilities.
First question: it seems I need to create a 'container' on each card to hold the abilities of that card; how does one do this, and what's it called? How/ where to write the abilities list that will go into these containers? First thought was the container should be a list, but I don't know what type of objects we should populate it with.
Second question: in order to handle effects that occur at specified times ("when drawn", "at end of turn", etc) I think I need to be able to create custom events, similar to the built in ones such as onCollisionEnter. These custom events would then be referenced in the scripts such as drawCardOnPlay. How to do this and what's it called?
Third question: is this unnecessary? Is there a more obvious way to do these things?
I'm certain this has answers somewhere (here, probably), but without knowing what these things are called I haven't made any progress. I've read some similar questions here but none that have addressed the implementation.


texts: Book and resource about vanilla OpenGL ES 2.0 development

texts:
I found this book but it talks about an SDK created by the author rather than pure simple OpenGL ES 2.0; this sounds more like a commercial to me than a good book for programming. I would like to start with just OpenGL ES 2.0 without talking about anything else: can you give me a good advice on this? A good book or on-line resource.

I'm also interested in cross platform development with OpenGL ES, in particular Android and iOS.


texts: How can I properly rotate a 2D vector in the "flipped" XNA client space?

texts:
In my 2d XNA game, because SpriteBatch treats world space as client space and has positive Y axis down and negative up, I've built my game's world space with that coordinate system too. However, I've hit a snag when I try to rotate a position around the origin using a matrix.

var p1 = new Vector2(95f, 40f);

var m = Matrix.CreateRotationZ(MathHelper.ToRadians(90));

var p2 = Vector2.TransformNormal(p1, m);

This results in p2.X == -40 and p2.Y == 95. If there's an object that is positioned relative to another object and that other object rotates, the child object gets swung around the parent object in the opposite direction because the matrix works in the positive Y axis up and negative down coordinate system.

What's the best way to account for this? Negate the Y value before and after transforming?

EDIT: To get more detailed I am trying to do a transformation like this, where child rotates with parent:

I though I would be able to multiply the matrices from the child object up through each of its parents' transform matrices in order to get its final world position, scale, and rotation that can be passed to SpriteBatch.Draw. Unfortunately the combined translations and rotations don't work out properly with the inverted Y axis.


texts: Transitioning through menus in Unity: what is the best option performance-wise?

texts:
I'm making a menu manager and I'm not sure what should I do to make a transition from one menu to the other. What is better to be used performance wise? Here is the step in my mind.

Simple enable or disable menu.
Change alpha 0 or 1.
Move the menu outside of canvas.

So what is better?