texts:
I'm new to OpenGL and don't really know how to rotate a terrain. For my graphics class, I have a project I need to do that is making a tire using OpenGL and work that we done in class (my framework is one of the labs that we did that introduced us to heightmaps and terrains).

I have this tire tread terrain (see picture) that I made and how I'm going to make the tire is by making lots of these tire terrains and rotate them to make the tire shape. I'm sure there is better ways to accomplish this but my professor recommended I do this. So I was wondering how I can rotate it.

The code below is my code for the terrain that is shown in the picture.
Thank you in advance for the help!

void TerrainScene()
{
    glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    //gluLookAt(0,g.moveup,g.movedown,  0,0,0,  0,1,0);
    //gluLookAt(g.movedown-50,8,g.moveup,  g.movedown-50,-2,g.moveup-40,  0,1,0);
    gluLookAt(g.movedown-50,70,g.moveup,  g.movedown-50,-2,g.moveup-40,  0,1,0);
    glLightfv(GL_LIGHT0, GL_POSITION, g.lightPosition);
    glColor3f(1.0f, 1.0f, 0.0f);
    glBegin(GL_TRIANGLES);
    glNormal3f(1.0f, 1.0f, 0.0f);
    float x = -25.0;
    float z = -25.0;
    float inc = 0.2;
    glColor3f(0.8f, 0.8f, 0.8f);
    for (int i = 0; i < 256; i++)
    {
        for (int j = 0; j < 256; j++)
        {
            float scale = 5.0;
            int tmp1 = (int)*(img[0].data + (i*img[0].width*3 + j*3));
            int tmp2 = (int)*(img[0].data + ((i+1)*img[0].width*3 + j*3));
            int tmp3 = (int)*(img[0].data + (i*img[0].width*3 + (j+1)*3));
            int tmp4 = (int)*(img[0].data + ((i+1)*img[0].width*3 + (j+1)*3));

            float e1 = -10.0 + ((float)tmp1 / 255.0) * scale;
            float e2 = -10.0 + ((float)tmp2 / 255.0) * scale;
            float e3 = -10.0 + ((float)tmp3 / 255.0) * scale;
            float e4 = -10.0 + ((float)tmp4 / 255.0) * scale;

            unsigned char rgb[3];
            getTerrainColor(i,j,1,rgb);
            glColor3ubv(rgb);
            Vec v1, v2, v3, norm;
            vecMake(x,      e2, z+inc, v1);
            vecMake(x+inc,  e4, z+inc, v2);
            vecMake(x,      e1, z,     v3);
            getTriangleNormal(v1,v2,v3,norm);
            glNormal3fv(norm);
            glVertex3f(x,     e2, z+inc);
            glVertex3f(x+inc, e4, z+inc);
            glVertex3f(x,     e1, z);
            vecMake(x+inc,  e4, z+inc, v1);
            vecMake(x+inc,  e3, z,     v2);
            vecMake(x,      e1, z,     v3);
            getTriangleNormal(v1,v2,v3,norm);
            glNormal3fv(norm);

            glVertex3f(x+inc, e4, z+inc);
            glVertex3f(x+inc, e3, z);
            glVertex3f(x,     e1, z);
            x += inc;
        }
        x = -25.0f;
        z += inc;
    }
    glEnd();
}


texts: I have read somewhere that sprites can detect the background color, but I don't remember where and how it's working. What I'm trying to do is just a function to detect if the sprite is on a special surface, that has a special color, instead of using collision dedection between objects. Help is preciated! Thanks!


texts: change the pivot point of an empty object

texts:
I have couple of objects and put them inside the empty object (to act as custom pivot point) .
Now, i want to change the pivot of the empty.
Normally i will unlink the objects first, move the empty to desired position and then link the object back (as child). But is it possible to change the pivot of the empty without unlink the objects first ?


texts:
As you can see from the title, I'm working on a game using pixel art. To archive that, I create a 160x90 texture, draw everything onto that and scale it up.
But the player in this game only moves about 10 pixels per second in some places. Luckily, the position isn't stored in pixels, but as a float, so the player can also be at (10.234, 3.76543). Because the map is big, the player is always centered on the screen and the world moves, instead. But as of my current implementation, I round the player's position to whole pixels in each update call. Otherwise, the engine would place all the world's sprites between the pyhsical pixels and they would be interpolated and look very unsharp and not very pixel-artish.

And there comes the problem: because the player moves just 10px/sec, the world only moves on the screen every 1/10 second. And that, of course looks like the game was running at 10 fps (it actually runs at 60fps).

So what is the recommended approach for that? Should I stick to what I current have got or should I let the graphic card do what it wants to do and let it interpolate the pixels and simply ignore the blurry effect.

PS: I know this question is similar but the difference is that in his case, he wants to avoid this staircase effect, while in my case, I want to avoid the lag


texts: Destroying cubes in combined mesh at runtime

texts:
How could I destroy cubes from a mesh? Once i've combined my cube to a single mesh, would it be possible to be able to destroy one of these cube but to keep a mesh ?
Ive seen a video where te person show a script to cut square or triangle shapes into a plane, so I tought it might be possible in 3d (Holistic3d is the person).
Does anyone have a script to do that ? because I have no clue how it could be done.


texts: How can I spawn particles around a point but inside a box?

texts:
There are particles in a box, the black circle representing the spawn point and the red circle representing the particles.

How could I spawn them so they don't spawn outside the box, and so that they are at an exact distance away from the spawn point and particles can slightly overlap.

Here is an example of what I'm trying to do:


texts: Are there any sample projects for Flashpunk?

texts: Are there any open source games using Flashpunk? The other big flash game library Flixel has a number of example projects, are there any equivalents for Flashpunk?


texts: Tracking how many people play my Unity game in which language?

texts:
In my game the user can change the language of the game and I'd like to know how many people play it in English, German, etc.
I'm using Unity, so possibly I would like to implement in Unity Analytics.
I was thinking about adding segments for the languages, but in that case if a user tries all languages, the user will appear in all languages' segments. So it won't really provide that much info.
A possible solution:

When the user changes language, we signal a database to decrease the old language's counter and increase the new language's counter.

But there must be an easier, built-in solution than this.


texts: How can shader code duplication be reduced in Unity?

texts:
In our current Unity project we have a few shaders that are basically just supersets of another shader. For example, we have a shader that performs lighting calculates with diffuse, normal, specular, and gloss maps, and a shader that performs lighting calculations with a diffuse, normal, specular, gloss, and glow map. The first is a subset of the second, but for performance reasons we've decided to separate them. This leaves us with heaps of duplicated code.

On top of this, I need to add stencil buffer operations to some of these materials, which is about 3 lines, but from what I can see, requires the entire shader file to be copied again.

How can we reduce this code duplication? In an object orientated language we'd used inheritence and polymorphism. What can we do here?


texts: How do I position a mesh just outside the camera view?

texts:
I want to slide in an object into view, coming from the right of the screen.

In order to achieve this, I need to position the object next to the camera view, so that it is still not visible, but close enough for a quick slide in.

For example, placing the object at X=1000000 (so that it is surely outside the camera view) for safety wouldn't work as it couldn't slide in quickly enough. For a reasonable slide, I would need to have it really close next to the camera view.

How could I calculate the object's position for that?

Thank you.

Edit:

Here is the script that I'm now using and which I'm still having problems with:

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

public class NewBehaviourScript : MonoBehaviour
{
    void Update()
    {
        float fDist = Mathf.Abs(Camera.main.transform.position.z - this.transform.position.z);
        Bounds b = BoundsFromTransform(this.transform);

        this.transform.position = GetPointLeftOfCamera(Camera.main, fDist, b.size.magnitude / 2);
    }

    public static Bounds BoundsFromTransform(Transform uTransform)
    {

        Bounds bounds = new Bounds(uTransform.position, Vector3.zero);

        foreach (Renderer renderer in uTransform.GetComponentsInChildren<Renderer>())
        {
            bounds.Encapsulate(renderer.bounds);
        }

        Vector3 nOff = bounds.center - uTransform.position;

        return new Bounds(nOff, bounds.size);
    }
    public static Vector3 GetPointLeftOfCamera(Camera camera, float distance, float goDiameter)
    {
        // 1.
        var ray = camera.ScreenPointToRay(new Vector3(0, camera.pixelHeight / 2f, 0));

        // 2.
        var borderPoint = ray.GetPoint(distance);

        // 3.
        var leftPlane = GeometryUtility.CalculateFrustumPlanes(camera)[0];
        var frustumLeft = leftPlane.normal;

        // 4.
        var halfDiameter = goDiameter / 2f;
        return borderPoint + frustumLeft * halfDiameter;
    }
    public static Vector3 GetPointRightOfCamera(Camera camera, float distance, float goDiameter)
    {
        var ray = camera.ScreenPointToRay(new Vector3(camera.pixelWidth - 1, camera.pixelHeight / 2f, 0));
        var borderPoint = ray.GetPoint(distance);

        var rightPlane = GeometryUtility.CalculateFrustumPlanes(camera)[1];
        var frustumRight = rightPlane.normal;

        var halfDiameter = goDiameter / 2f;
        return borderPoint + frustumRight * halfDiameter;
    }
}


texts: How to move bezier curve points along circle to form a symmetric curve at center

texts:
From the image below, A is an open bezier curve with it's points positioned to represent a circle. AP3 and AP1 have the same position.
From B, How can I move the points (AP1 and AP3 along the bigger circle of radius r whiles the CP's reduce in length as CP1 and CP4 also rotate) till they form a symmetric bezier curve at the center of the bigger circle marked as the red curve?


texts: How to determine polygon, texture size, and frame time budgets for a game on a custom engine?

texts:
I'm currently working on a mid-size group of students developing a classic dungeon crawler game using own engine. I have the task to create a document where it tells:

What polycount and texture size limits artists should have
How much time each module of the engine should take

I know that this data is not to be exact by any meanings, because priorities would change depending of the needs of the game. I could try to drop some art in a scene, and seeing how much the framerate is impacted. I can take the 16 miliseconds of a 60fps game and distribute them among all modules, trusting my gut.

The problem is that I do not feel as this method is the correct, and I do not found any references of how I could distribute miliseconds (even for a blurry guide to follow), or how I could do some estimation of what limits the art (and the design) should have, based on our tech.

How can I make these estimates?


texts: Changing text occurs error: move initialization code to the Awake or Start function

texts:
I have GameManager class that has Log method:

using UnityEngine;
using UnityEngine.UI;

public class GameManager: MonoBehaviour {
    public static GameManager Instance;
    [SerializeField] private ScrollRect m_GUIConsoleContainer;
    [SerializeField] private UnityEngine.UI.Text m_GUIConsole;
    ...

    void Awake() {
        Instance = this;
    }

    ...

    public void Log(string message) {
        m_GUIConsole.text = m_GUIConsole.text + message + "\n";
    }
}

GameManager class has static instance, so I can invoke Log method in anywhere like this:

GameManager.Instance.Log("Helloworld");

However it works only first time. After invoke Log again, Unity gives me this error message:

  get_isActiveAndEnabled can only be called from the main thread.
  Constructors and field initializers will be executed from the loading thread when loading a scene.
  Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
  UnityEngine.UI.Text:set_text(String)

I assigned reference of m_GUIConsoleContainer and m_GUIConsole in inspector, but I don't get it what this means and why it happens. Just using Debug.Log() or print() works without any error.

How should I avoid this error message? Using Unity 2018.2.1f1.

p.s. Error coming from here, another class called NetworkManager:

void OnReceivedBytes(IAsyncResult result) {
    try {
        if(m_Socket == null) {
            return;
        }

        int resultLength = m_Socket.EndReceive(result);

        if(resultLength == 0) {
            Shutdown();
            return;
        }

        Log("Received: " + m_RecvBuffer[0]);  <<- Error coming from here
        ...
    }
    ...
}

And this is where it call OnReceivedBytes:

using UnityEngine;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;

public class NetworkManager: MonoBehaviour {
    private Socket m_Socket;

    void Start() {
        m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        m_Socket.Connect("localhost", 1337);

        if(m_Socket.Connected) {
            Log("Connected.");

            m_Socket.BeginReceive(
                m_RecvBuffer,
                0,
                m_RecvBuffer.Length,
                SocketFlags.None,
                new System.AsyncCallback(OnReceivedBytes),
                null
            );
        }
        else {
            Log("Failed to Connect.");
        }
    }

    ...
}


texts:
How is it possible to simulate water in our game?

I want to make rivers and lakes for my game but I don't know how to make the waves and make the water look like it's moving.

How would I do it?


texts: current value of x for vector2 game object

texts:
I just need to push my game object in y direction not in of its x position,I need to assign it a new position but unable to access its current x position value so that can make it fix on its x position... please help

I tried this:

Vector2 curScreenPoint = new Vector2 (need the current x position of game object , Input.mousePosition.y);

Vector2 curScreenPoint = new Vector2 (0, Input.mousePosition.y);
     Vector2 curPosition = Camera.main.ScreenToWorldPoint (curScreenPoint);
    transform.position = curPosition;


texts: How does one optimize an HTML5 Canvas and JavaScript web application for Mobile Safari?

texts: I've created an HTML5 Canvas and JS game that runs great on a desktop or laptop in Chrome (30fps), but on mobile Safari I only get around 8 fps. Are there any simple tips or tricks to increase the framerate?


texts: Issue with distinguishing levels in isometric game

texts:
Possible Duplicate:
  How can I change this isometric engine to make it so that you could distinguish between blocks that are on different planes?

I'm working on an isometric game however I am having trouble visually distinguishing between levels in the game.

Take the example below, the first image shows concrete blocks at ground level and the following images show an attempt to build a few blocks a level above. As you can see the level above is visually swallowed the one below.

I've tried shading to make lower levels darker with respect to camera, but this doesn't work that well.. any ideas?


texts:
I am trying to test out the new Navmesh tools as of Unity 2018.1
So i have a simple scene with a plane:

Then i have the following script:
    public class SpawnObject : MonoBehaviour
{
    public GameObject ObjectToSpawn;
    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.name == "floor")
                {
                    Instantiate(ObjectToSpawn, hit.point, Quaternion.identity);
                    NavMeshBuilder.BuildNavMeshAsync();
                }
            }
        }
    }
}

This spawns a prefab and then i attempt to update the navmesh however nothing really happens:

The cube I am spawning has the following properties:

Can anyone tell me what I am doing wrong?


texts:
I finished my game programming but I have small problem, please help me I want to finish it completely.
I am starting background music when the user goes to the PlayScreen and when the kid in the game dies, the background music stops and starts game over music and move to game over screen, then the user goes to the menu screen and choose the level he wants then go back to the PlayScreen but the back music isn't working again, I didn't know how to solve it although the music is working very well when start the game and when the user win the level, but it is not working when the kid dies. here is the code where I stop the music in the kid class:

public State getState()
    {
        //Gdx.app.log(Float.toString(b2body.getLinearVelocity().x),"hi");
        if ((Hud.getTime()<0)) {
            Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
            Fruits.manager.get("music/fail.mp3", Sound.class).play();
            collectoIsDead=true;
            Filter filter = new Filter();
            filter.maskBits = Fruits.NOTHING_BIT;
            for (Fixture fixture : b2body.getFixtureList())
                fixture.setFilterData(filter);
            b2body.applyLinearImpulse(new Vector2(0, 5f), b2body.getWorldCenter(), true);
            //b2body.applyLinearImpulse(new Vector2(0,-2.5f), b2body.getWorldCenter(), true);
            Hud.setTime();// to prevent the action of applying more times

            return State.DEAD;
        }
        if ( Rockhit()) {
            Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
            Fruits.manager.get("music/fail.mp3", Sound.class).play();
            collectoIsDead=true;
            Filter filter = new Filter();
            filter.maskBits = Fruits.NOTHING_BIT;
            for (Fixture fixture : b2body.getFixtureList())
                fixture.setFilterData(filter);
            b2body.applyLinearImpulse(new Vector2(0, 5f), b2body.getWorldCenter(), true);
            //b2body.applyLinearImpulse(new Vector2(0,-2.5f), b2body.getWorldCenter(), true);
            return State.DEAD;
        }
        if((Hud.getTime()==0&& Hud.getScore()>=(level*30)+50)|| (Hud.getScore()>=(level*30)+50)) {
            Fruits.manager.get("music/Backmusic.ogg", Music.class).stop();
            Fruits.manager.get("music/cheering.mp3", Sound.class).play();
            return State.SUCCESS;
        }
        if (b2body.getLinearVelocity().x!=0)
            return State.RUNNING;
        else
            return State.STANDING;
    }

And here is the code where I start the music in the constructor of the PlayScreen:

public PlayScreen(Fruits game, float level)
    {
        this.level=level;
        this.game=game;
        gamecam=new OrthographicCamera();

        gameport=new FitViewport(Fruits.V_WIDTH/Fruits.PPM,Fruits.V_HIEGT/Fruits.PPM,gamecam);

        hud=new Hud(game.batch,level);
        atlas=new TextureAtlas("mypack.pack");
        mapLoader=new TmxMapLoader();

            map=mapLoader.load("world10.tmx");

        renderer=new OrthogonalTiledMapRenderer(map,1/Fruits.PPM);
        gamecam.position.set(gameport.getWorldWidth()/2,gameport.getWorldHeight()/2f,0);
        globalcounter=100;
        world=new World(new Vector2(0,-10),true);
        b2dr=new Box2DDebugRenderer();
        new B2WorldCreator(this);
        player=new Collector(world,this,level);
        world.setContactListener(new WorldContactListener());
        controller=new Controller(game.batch);

        music=Fruits.manager.get("music/Backmusic.ogg", Music.class);
        music.setLooping(true);
        music.play();
    }


texts: Disjointed bones in 3ds Max - Are they a problem?

texts:
The title sums up my question fairly well. I'm working with a biped, and I'm not sure whether to put the extra effort into connecting all the bones, or just to leave spaces between each of them. What do you think?

Screenshot:

http://i.imgur.com/pfbLSDt.png


texts: Having trouble going from the menu I created w/ Android normally to my LibGDX game file

texts: So I wanted to use Android Studio to create the menu for my game so I created a button with an onClick method that included the Intent i and startActivity(i) but when I clicked the button the app would just crash on me


texts: What's the best for ground check? I have a capsule player and I'm using the raycast technique but it's not accurate when it comes to slopes. So what's better? Overlapping, Raycasting, CheckCapsule, or CapsuleCasting?


texts: A controlled trapezoid transformation with perspective projecton

texts:
I'm trying to implement a controlled trapezoid transformation in Adobe Flash's ActionScript using the built-in perspective projection facility. To give you an idea of how the effect looks like:

http://i.stack.imgur.com/Pa1T0.jpg

I've been searching for a solution for a few days now and, apart from the tessellation alternative which produces poor quality results, no one has tried to employ perspective projection to achieve this effect. It's maybe because it requires solving some math, which is something I hope you could help me with.

So Flash uses a simple frustum model with a viewpoint, projection plane, and focal length, which is the distance from the viewpoint to the projection plane.

http://i.stack.imgur.com/1WmGa.jpg

There is also fieldOfView but it should be of no importance as its meaning appears to be overridden by focalLength (at least it's value makes no difference in my ActionScript experiments as long as the focal length is specified).

The rectangular piece of graphics is located right on the projection plane so that the middle point of its top edge is located in the projection center. To achieve the effect, the rectangle is rotated by some angle.

(Sorry, the forum wouldn't let me post more links to the drawings. Could anyone please edit it to put the last 2 imaged referred at the end of the source right here.)

<>

The question is, what should be the values of focal length and angle so that new height and new bottom width satisfy some given values that are desired for the effect? Or speaking mathematically:

Given:

a frustum with focal length
a rectangle with its width and height, which is pinned to the projection plane (z=0) of so that the midpoint of the rectangle's top edge is located right in the projection center of the frustum
the needed new height and new bottom width of the rectangle after it's rotated and projected onto the projection plane

Unknowns to be found and applied to the perspective projection in order to get the desired new height and new bottom width:

the focal length of the frustum
the angle of rotation

If I missed out any other parameters or added any redundant ones, please correct me.

Also, is it possible to control the effect just by the angle with which the sides of the rectangle should be projected on the projection plane (the angle between the projected rectangle's side and its top edge) provided that the new height remains some constant value?


texts:
I'm using blender to model, rig and animate my character for a Unity game, but there is something that I can't figure out by myself neither find on the internet, for example:

Lets say the main character is able to punch npcs and I want that punch aimed to the face but not all npcs have the same height.

How can the animation be adjusted to handle this?

Inverse kinematics seems to be the solution but to this date I couldn't find any good example or information about this subject better than "Check this box to fix the animation for stairs" and so on.


texts:
So I am fairly new to programming and I am trying to learn by making a simple game. I watched to different videos on ray cast shooting and one of them has code for bullet hole decals that I wanted to add to the other one but I was to sure, about how I would go about doing that. I would really appreciate any help than anyone can give with this problem, as it would really help me lean some more about programming. The first set of code is the one I want to insert the other code into.

Thanks, Nova

#pragma strict

var Effect : Transform;
var TheDammage = 100;

function Update () {

 var hit : RaycastHit;
 var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width*0.5, Screen.height*0.5, 0));

 if (Input.GetMouseButtonDown(0))
 {
  if (Physics.Raycast (ray, hit, 100))
  {
   var particleClone = Instantiate(Effect, hit.point, Quaternion.LookRotation(hit.normal));
   Destroy(particleClone.gameObject, 2);
   hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
  }
 }

}

var bulletTex : GameObject[]; // creates an array to use random textures of bullet holes

function Update () {

   var fwd = transform.TransformDirection(Vector3.forward); //casts our raycast in the forward direction

   var hit : RaycastHit;

   Debug.DrawRay(transform.position, fwd * 10, Color.green); //drays our raycast and gives it a green color and a length of 10 meters

if(Input.GetButtonDown ("Fire1") && Physics.Raycast(transform.position, fwd, hit, 10)){ //when we left click and our raycast hits something
         Instantiate(bulletTex[Random.Range(0,3)], hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal)); //then we'll instantiate a random bullet hole texture from our array and apply it where we click and adjust// the position and rotation of textures to match the object being hit
}


texts: How to build list of items available in World of Warcraft?

texts:
There are a number of non-Blizzard sites that show a complete list of available items in World of Warcraft (such as wowhead, etc). I would like to know the best (easiest) way to compile a similar list.

I believe some sites are based on user-entered input, which I would like to avoid. Looking at the lua API, it seems that there are functions to get a list of items, but it's not clear if I can just download everything (I remember a reference to throttling somewhere, can't find it now). Does anyone have code samples that would do this, or links to source?

Also, Eve Online has made a database of items available (and I do mean SQL database file for download, not the Armory) - is there anything similar for Wow?

I'm just looking for the names and stats, not the graphic icons.


texts: If I have a player character that can move 8-directionally, I can set the rotation of the player to face the direction of movement. But if I want to smoothly rotate to a direction, sometimes the player will take the "long way around" (i.e., player is at -90 degrees, facing right; I press S and it will rotate 270 degrees to be at 180 degrees, facing down). How can I fix this? I tried adding 360 to the desired angle until it was within 90 degrees, but that didn't work (probably just because I'm too tired, though). Any help is appreciated!


texts: Does SDL_SetThreadPriority work with std::thread

texts: I'm trying to set the priority of my threads so that my UI thread can be given priority over background calculations. I noticed that SDL has a SDL_SetThreadPriority method, however I still prefer the standard std::thread syntax rather than SDL_CreateThread. Does SDL_SetThreadPriority work with threads created with std::thread, or do I need to update everything to use SDL_Thread?


texts: Unity 2D play animation with flipX then enabling and disabling GameObject "locks" flipX

texts:
I have a GameObject with an Animator that contains many different animations. In C# I switch between these animations with animator.Play("AnimName"). Some of the animations have the flipX property checked, so I can use the same sprite for two different directions.

This works well, but I have one animation where after it is done I call gameObject.SetEnabled (false) then re-enable it a short while later. I achieve this through an event at the end of the animation which calls a method in my script.

For some reason, if the last animation I played before disabling the object had the flipX property checked, then all the other sprite animations will be flipped after it is reenabled. I can fix this by adding the flipX property to the other animations then unchecking it, but I don't want to have to go through all my animations to add an unchecked property.

This seems like a bug to me, but if it's not, is there some way I can change the behavior?


texts: How can a game engine's renderer be visually compatible with Maya's?

texts: Say you create some model in say Maya, you apply all kinds of effect to the model and then export the file. Then the game engine has to load the file and render it, so surely the game engine needs the same renderer as Maya's to reproduce the effects created in Maya?


texts:
I am working on face detection in unity.I have tried out a face tracking sample from the below link.It worked fine

https://github.com/marcteys/unityFaceTracking

The problem is that,when I runned the above project,Am show with a separate camera view window for detection. But when we consider unity android,the tracking should be done through phone camera.

Is there any option other than OpenCV.

Please help me out


texts:
I am new and vey much interested  in android stuff. please help on how and where to start the development of game.

Any Prerequisite for that.

Awaiting for reply.


texts: Is there a way to for example in vertex shader cull current vertex? I have my own grass system and I would like to cull straws that are further away than some distance but I can't use camera culling because grass is drawn in chunks and it hides a whole chunk.


texts: Draw multiple times same object but translated and rotated

texts:
I want to draw lots of spheres in different locations and orientations with Opengl4 and JOGL. As the vertexes and colours are the same for all of them, I have just one array for vertexes and another for colours. For the positions and orientations, I have another big matrix where I have all data for all spheres.

In principle, drawing one with glDrawArrays is not a problem but for severals, I have read that I should use glDrawArraysInstanced instead. My problem is that I am a bit confused about how to apply each transformation for my particles. How should I introduce this array into the shader? Should I send the matrix model after doing the transformations in the cpu or should I send the positions and orientations and transform them inside the shader? How do I connect the data to the shader? How should the shader look like?


texts: Is story more important or the gameplay more important?

texts:
Read this Slate article. In particular, the following struck me:

When he looks at video games from a critical distance, Bissell is concerned mainly with their lack of narrative meaning. Games ask us to save the princess, save the country, save the world, save ourselves—but no one plays games to achieve those ends. We play for the puzzle, for the physics, for the sense of being embedded in a fully realized world. Indeed, for me, the "story" usually seems like filler, even in games like Grand Theft Auto and RDR [Red Dead Redemption], whose stories are smarter than the rest of the video-game pack. RDR begins and ends every mission with cleverly scripted movielike "cut scenes" that provide some explanation for why your character is doing what he's doing—but the game also lets you skip the scenes, which I usually elect to do. Thus I can't really explain why my character is doing what he's doing. The real answer is he's doing it because I am making him do it, and I am making him do it only because I am having fun.
"This is one of the most suspect things about the game form," Bissell writes. "A game with an involving story and poor gameplay cannot be considered a successful game, whereas a game with superb gameplay and a laughable story can see its spine bend from the weight of many accolades—and those who praise the latter game will not be wrong." What's the solution to this quandary? Should games invest more in story, in an attempt to bring us narratives that are on the level of those of the other popular arts? Or should games abandon story—is the video game, as a form, simply incompatible with traditional concepts of narrative, and must game designers instead find other ways to invest their creations with lasting meaning?

As if Bissell's uncertainty is echoing throughout the game industry, there has arisen a tendency to make many big-budget blockbuster games heavily story-driven. Even Starcraft II has a fairly story-driven campaign.
Is a game without a high-quality narrative bereft of true value and meaning? Must games have any meaning at all in the literary sense in order to be considered worthwhile forms of entertainment? What about emergent narratives, where the player has a decisive role in determining the plot (ideally much more decisive than we've seen in any games so far released)? If games do not need a higher literary meaning, do they at least need to have some lasting emotional significance for the player?
Those are just some thoughts that the article raised. The real question can be summed up like this: what is the true value of a video game? Is a game to be valued on its dynamic interaction with the player, on its ability to present a narrative in a way other mediums cannot, or on its ability to provide simple pleasure?


texts:
I have a Unity project, which heavily relies on the marching cubes algorithm. Because this algorithm doesn't return the triangles in order, I can only index them in the order they are present in the vertices array.

For example:

vertices: {Vector3(0, 0, 0), Vector3(1, 0, 1), Vector3(1, 1, 0)...}
triangles: {0, 1, 2, 3...}

Because of this, Unity's RecalculateNormals method doesn't work properly and it gives me the following result:

Is there anyway I can make the normals smoother? Keep in mind, that I need to possibly recalculate these vertices everytime the values change, so I can't rely on very heavy methods.


texts: How to structure a game that continue even when closed?

texts:
I'm developing a Unity based game purely for fun but I'm stuck with a problem.
How can I implement a system that keep my game running even when is closed? I don't want to HAVE IT running when it's closed, but I was thinking to add some kind of timer and compute the logic of the game with the time difference between (LAST_SESSION)-(ACTUAL_SESSION).

But how can I implement this? The thing is, how can I "accelerate" the game when I open it so that it's current state is equal to what would have been if I would not have closed it?

EDIT: The game is a sort of RTS. You control a base that has some number of entities that can move independently. Each entity has some kind of job like mine minerals, defend the base from enemy AI, build a structure. The mechanics are the interactions between each entity and the world.

I have a main loop where I update every entity, one at a time. I was thinking that I could do some kind of Load function that calls that main loop with a time_elapsed variable and with every iteration lower this variable by Time.deltaTime or something like that, and when it reaches zero I can start the game.

Sorry for my bad english.


texts:
I'm currently develop a facebook mafia like PHP game(of course, a light weight version), here is a simplify database(MySQL) of the game

id-a           <int3>  <for index>
uid            <chr15> <facebook uid>
HP             <int3>  <health point>
exp            <int3>  <experience>
money          <int3>  <money>
list_inventory <chr5>  <the inventory user hold...some special here, talk next>
... and 20 other fields just like reputation, num of combat...

*the number next to the type is the size(byte) of the type

For the list_inventory, there have 40 inventorys in my game, (actually, I have 5 these kind of list in my database), and each user can only contain 1 qty of each inventory, therefore, I assign 5 char for this field and each bit of char as 1 item(5 char * 8 bit = 40 slot), and I will do some manipulation by PHP to extract the data from this 5 byte.

OK, I was thinking on this, if this game contains 100,000 user, and only 10% are active, therefore,

if use my method, for the space use,

5 byte * 100,000 = 500 KB

if I use another method, create a table user_hold_inventory, if the user have the inventory, then insert a record into this table, so, for 10,000 active user, I assume they got all item, but for other, I assume they got no item, here is the fields of the new table

id-b     <int3>  <for index>
id-a     <int3>  <id of the user table>
inv_no   <int1>  <inventory that user hold>

for the space use,

([id] (3+3) byte + [inv_no] 1 byte ) * [active user] 10,000 * [all inventory] * 40 = 2.8 MB

seems method 2 have use more space, but it consume less CPU power. Please comment these 2 method or please correct me if there have another better method rather than what I think.

Another question is, my database contain 26 fields, but I counted 5 of them are not change frquently, should I need to separate it on the other table or not?

So many words, thanks for reading :)


texts: Unity - Texture on Plane fades at angle - Generating mipmaps?

texts:
Good day, I seem to have run into a problem which I can't find an answer to. I'm making a World Editor for my project, and generating a grid plane which the user can modify. Whenever I rotate the camera as seen below, to a more side view angle, the grid texture fades out.

I have changed Aniso levels, tried at different quality settings, also different shaders for the texture.

At the moment, I'm using the Unlit/Transparent Cutout shader which gives a crisp look on the grid. The texture resolution is for width and height mapSize(64 > 254)*gridDetail(4>32). The same results is given no matter the detail size on the texture.

It does appear that the center of the plane gets the most faded as opposed to the sides.

EDIT: Okay, so I found out what's the problem, now here's my question, how can I generate mipmaps for the texture? (The texture is created with the following code(unoptimized I know):

using UnityEngine;
using System.Collections;

public class MyScript: MonoBehaviour
{
    public int sizeX,sizeZ;
    public int gridDetail;
    public Color smallGridColor = Color.white;
    public Color largeGridColor = Color.yellow;
    public bool drawSmallGrid,drawLargeGrid;

    Texture2D gridTexture()
    {
        Texture2D gridTex = new Texture2D(sizeZ * gridDetail + 1, sizeX * gridDetail + 1);
        Color[] gridColor = new Color[gridTex.width * gridTex.height];
        Color[,] gridColor2 = new Color[gridTex.width, gridTex.height];
        for (int i = 0; i < gridTex.width; i++)
        {
            for (int x = 0; x < gridTex.height; x++)
            {
                gridColor2[i, x] = Color.clear;
            }
        }

        if (drawSmallGrid)
        {
            for (int i = 0; i < gridTex.height - 1; i += gridDetail)
            {
                for (int j = 0; j < gridTex.width - 1; j++)
                {
                    gridColor2[i, j] = smallGridColor;
                }
            }
            for (int i = 0; i < gridTex.width; i++)
            {
                for (int j = 0; j < gridTex.height; j += gridDetail)
                {
                    gridColor2[i, j] = smallGridColor;
                }
            }
        }

        if (drawLargeGrid)
        {
            for (int i = 0; i < gridTex.height - 1; i += gridDetail * 4)
            {
                for (int j = 0; j < gridTex.width - 1; j++)
                {
                    gridColor2[i, j] = largeGridColor;
                }
            }
            for (int i = 0; i < gridTex.width; i++)
            {
                for (int j = 0; j < gridTex.height; j += gridDetail * 4)
                {
                    gridColor2[i, j] = largeGridColor;
                }
            }
        }

        for (int i = 0; i < gridTex.height; i++)
        {
            for (int j = 0; j < gridTex.width; j++)
            {
                gridColor[i * gridTex.width + j] = gridColor2[i, j];
            }
        }

        gridTex.SetPixels(gridColor);
        gridTex.filterMode = FilterMode.Point;
        gridTex.wrapMode = TextureWrapMode.Clamp;
        gridTex.alphaIsTransparency = true;
        gridTex.Apply();

        return gridTex;
    }
}

Any ideas?


texts: Which is the right way to build a OpenGL Projection Matrix

texts:
This time I'm trying to learn the core of matrix transformations. I dont like the idea to using a Math library and dont understand what is hapening on background, because this I'm having some dificulties with Projection Matrix. I've read many tutorials that explain how Projection Matrices show be and what they do. But at this moment I got two different Projection Matrices and I dont know which should I use.

Look at this, frist from this tutorial:

private float near = 0.1f;
private float far = 100.0f;
private float fov = (float)Math.toRadians(45.0);
private float aspect = (float) 400 / (float) 300;

private float f = (float)Math.tan(fov / 2.0f) * near;
private float Sx = (2.0f * near) / (f * aspect + f * aspect);
private float Sy = near / f;
private float Sz = -(far + near) / (far - near);
private float Pz = -(2.0f * far * near) / (far - near);

projection = new Matrix4f(new float[]{
        Sx,   0.0f, 0.0f, 0.0f,
        0.0f, Sy,   0.0f, 0.0f,
        0.0f, 0.0f, Sz,   -1.0f,
        0.0f, 0.f,  Pz,   0.0f,
    });

Now look this second, from this tutorial:

private float near = 0.1f;
private float far = 100.0f;
private float fov = (float)Math.toRadians(45.0);
private float aspect = (float) 400 / (float) 300;

private float f = 1.0f / (float)Math.tan(fov / 2.0f);
private float Sx = f / aspect;
private float Sy = f;
private float Sz = -(far+near) / (far-near);
private float Pz = -(2.0f * near * far) / (far – near);

projection = new Matrix4f(new float[]{
        Sx,   0.0f, 0.0f, 0.0f,
        0.0f, Sy,   0.0f, 0.0f,
        0.0f, 0.0f, Sz,   -1.0f,
        0.0f, 0.f,  Pz,   0.0f,
    });

So, which is correct? Or if both are correct, there is some recommendations? I think the second one is more easy to read.

P.S.: In my code i'm using Right Handed System and Column-Major Matrices.

Thanks for your attention!


texts: Box2d contant speed before and after collision

texts:
I want to make my body fly at constant speed, how to make it fly at constant speed before and after collision? I set restitution of my body to 1.0 but after some direct and powerful collisions my objects begins to slow, I want it to fly same speed as before. I heard this can be done by setting liner damping of the object, I think it can prevent only from fast flying objects not slow.
 Thanks in advance.

Edit* I can simply modify velocity of the object every frame, is it a solution?

var velocity:b2Vec2=b.GetLinearVelocity();
var speed:Number=velocity.Length();
var ratio:Number=circleSpeed/speed;
velocity.Multiply(ratio);
b.SetLinearVelocity(velocity);


texts: Capping framerate independently of logic updates in single-threaded Android Gameloop

texts:
My game is currently using the below game loop (this is an OpenGL ES 2.0 game, therefore the loop-work takes place on the rendering thread in the provided onDrawFrame method).

Currently my loop provides (and will need to continue providing) the following:

The loop allows me to cap logic updates to an arbitary value (which I have set to 60) - so 60 updates per second.  This allows my game to run at the same speed (ie, not too fast) on all devices I've tested so far. (I'm not concerned with a device not being able to handle 60 ticks per second as I'm yet to find one that can't and I've tested this on some very old devices, they all run perfectly fine).
If a device can't handle the rendering demands (much more likely), the loop will allow it to drop frames so it can catch up.  All the while, allowing the logic/physics tics to carry on running at a smooth 60 ticks per second.

The only remaining problem with the loop is that it renders 'flat out' - so, out of the 20+ devices on which I've tested this, there are 3 main groups:

VSYNC'd at 60 FPS - (for example Google Nexus 10)

VSYNC'd at 30 FPS - (eg, generic Android tablet)

No VSYNC          - (Samsung Galaxy Ace Mk1)

So, when running on say, a VSYNC 60FPS device, I generally get 60 logic updates per second and 60FPS.

On a VSYNC 30FPS device, I get 60 Logic updates and 30FPS

On a No VSYNC device, I get 60 Logic updates and 'The Sky is the limit' FPS (on my Ace, it can get up to 90-100 FPS).

What I really want my loop to do, is limit the rendering.  In my case I want to run my physics at 60 ticks per second and render at 30FPS.

I want to do this because rendering flat out is eating battery and heating up devices unnecessarily.  If my rendering is capped at 30FPS I would think it would help a lot in this case no?  I need my physics to keep running at 60 ticks,  reducing that isn't really an option (I've tried it and it causes a few glitches with collision and sprites that move very fast over tiny distances) but I digress....

I've been trying all day to figure out how to do this so that:

On all devices (that can handle at least 30FPS or greater) it will always run at 30FPS. (so even if VSYNC'd to 60FPS).

The loop

@Override
public void onDrawFrame(GL10 gl) {

    //Grab time
    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime; //Amount of time this entire frame took
            if ( frameTime > (dt*25))
                frameTime = (dt*25);
            currentTime = newTime;

            accumulator += frameTime;

            //Update logic while
            while (accumulator >= dt){
                saveGameState();
                updateLogic(dt);
                t += dt;
                accumulator -= dt;
            }

            interpolation = (float) (accumulator / dt);

            render(interpolation);

}

Sleep time?

As the loop renders whenever it's not updating, I'm thinking I need a way to 'sleep' once it's called and finished render(interpolation) until it's ready to go again.

I tried putting this following code in after render(interpolation) (within onDrawFrame - where newTimeMillis is System.currentTimeMillis() grabbed at the start of onDrawFrame) but I'm not really sure how this would work when onDrawFrame is called every 16.66666666666667MS on devices that have VSYNC capped at 60FPS.  I've getting really confused over this and would appreciate if someone could give me a clue as to what kind of code I need to inject into my loop to achieve that which I'm trying to achieve.....(something I incorrectly assumed would a simple thing to do!!)

            render(interpolation);

            long sleepTime = (System.currentTimeMillis()-(newTimeMillis));
            if (sleepTime<33.33333333333333){
            try {
                Thread.sleep((long) (33.33333333333333-(sleepTime)));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
}


texts:
I have my editor configured to use git as my VCS. I have my own server in which the repo is hosted.

I followed the GIT with Unreal 4 guide.

My problem is that I cannot find the "Check Out" option in the right-click menu of any blueprint/asset. My VCS menu only shows Refresh, History and Diff Against Depot.

Am I wrong if I think that when modifying any asset, my teammates shall check out the asset in order to lock it for editing? If so, how to do that? I tried with the auto-checkout on asset modification but that's not working as expected either, since I modify an asset and it's not being checked out.

Any ideas on how to properly configure GIT to work as expected?

Moreover, how to make a push from the editor? I seem to be able to make the commit by "Checking In" some asset, but can I make the push to the remote repo from the editor itself?

Many thanks.


texts: How can I dissolve using dynamic mask objects?

texts:
I want to Implement dissolve shader like this youtube video

as you can see minions projected light on house to burning it out.

I like to know how to make a similar effect.


texts:
I experienced this weird lightmapping bug in my game that causes some models to have glowing artifacts on their surface. These artifacts "move" around, when I edit the UVs of the model in Blender, so I assume that it has something to do with them. I took a few screenshots to hopefully clarify the issue.

Engine used: Unity 2019.1.4f1
3D Software: Blender 2.79b

If you need any other screenshots or something, let me know. Thank you in advance!

Lightmap Bug (lights off):

Lightmap Bug (lights on):

Models without Lightmaps baked:

Unity Lightmapper Settings:

Tree model in Blender with UVs:

Model Configuration in Hierarchy:

Model Asset Configuration:


texts:
I am learning to use Unity, and found I disliked the way moving around the scene editor is implemented. The left and right arrow keys move the scene "camera" left and right as expected, but the up and down editor moves forwards and backwards. Is there a way to change the controls to make it more like a "traditional" WASD movement, similar to how Minecraft on touch devices does it (up, down, left, and right moves exactly as it sounds, and rotation is by clicking and dragging the mouse)?
Thank you for your time.


texts:
I'm doing a hobby game project using Visual Studio 2015 and XNA, via the MonoGame implementation. I wanted to do some unit testing, as I recently discovered this feature in Visual Studio, and want to get a feel for how it can be used.

The problem is, I can't get it to work with the XNA Game object, or anything derived from it.

This is a simple instantiation test I made:

[TestMethod()]
public void MyTest()
{
    try
    {
        MyObject Test = new MyObject();
    }
    catch
    {
        // Fail the test if any exception occurs in the constructor.
        Assert.Fail();
    }
}

Whenever I use my own object in place of MyObject, the test passes.  When I use MyGame (derived from Game and with my own properties/methods), the test fails.  I've tested the same object in the debugger, and it doesn't throw an exception.

Any idea what I'm doing wrong, or is the Game class just incompatible with Visual Studio unit testing?


texts: Game engine design choice, favour data oriented design over oop?

texts:
I have a scene, in the scene there are multiple systems. Transformsystem, collidableSystem etc ... Currently, these do nothing except returning a bool if the parameter component matches the system:

bool DrawableSystem::match(Component* component)
{
    return dynamic_cast<Drawable*>(component) != 0;
}

The parent class handles everything else:

class System
{
protected:
    std::vector<Component*> _components;
    std::map<int, int> _idToOffset;
public:
    System();
    ~System();

    void initiate();
    void update(long);
    void remove(unsigned int);
    Component& getComponent(unsigned int);
    bool contains(unsigned int);
    void add(Component*, unsigned int);

    virtual bool match(Component* component) = 0;
};

The match method is used in scene when i for example instantiate an entity (I dont really have an entity class, its just a vector of components). It returns the id which is used when interacting with the components representing that entity.

unsigned int Scene::instantiate(std::vector<Component*> components)
{
    _currentId++;

    for (Component* component : components) {
        for (System* system : _systems) {
            if (system->match(component)) {
                system->add(component, _currentId);
                break;
            }
        }
    }

    return _currentId;
}

This will make it so that the vector _components in each system consists of only components associated with that system.

The current design is very maintainable and extendable, i don't have to modify any code in scene when adding a new type of component or system as you can see:

Scene::Scene() {
    _currentId = -1;
    _systems.push_back(new TransformSystem());
    _systems.push_back(new DrawableSystem());
    _systems.push_back(new CollidableSystem());
    _systems.push_back(new ScriptableSystem(*this));
}

Scene::~Scene()
{
    for (System* system : _systems) {
        delete system;
    }
}

void Scene::initiate()
{
    for (System* system : _systems) {
        system->initiate();
    }
}

void Scene::update(long dt)
{
    for (System* system : _systems) {
        system->update(dt);
    }
}

unsigned int Scene::instantiate(std::vector<Component*> components)
{
    _currentId++;

    for (Component* component : components) {
        for (System* system : _systems) {
            if (system->match(component)) {
                system->add(component, _currentId);
                break;
            }
        }
    }

    return _currentId;
}

void Scene::addComponent(Component* component, unsigned int id)
{
    for (System* system : _systems) {
        if (system->match(component)) {
            system->add(component, id);
        }
    }
}

bool Scene::exists(unsigned id)
{
    for (System* system : _systems) {
        if (system->contains(id)) {
            return true;
        }
    }
    return false;
}

void Scene::destroy(unsigned int id)
{
    for (System* system : _systems) {
        if (system->contains(id)) {
            system->remove(id);
        }
    }
}

But from what i've heard oop should not be used extensively like i do when designing a game engine.

I tried a purely data oriented design in the beginning but it started to get difficult to modify when i got up to around 4 different systems / component types.

Worth mentioning is that this is my first time making a game engine or anything remotely that complex so i can't really plan everything out in detail and just implement it by looking at an UML diagram. I constantly come up with better architectural choices for how the systems / scene communicate, additional method that could be useful etc ...

Do you gain so much in performance using a data oriented approach that reducing maintainability / modifiability would be worth it? It does not feel like it at all in my case, but i'd really like to learn how they do it in the industry and start learning "the right way" from the start. Are there other potantial gains with dod that i haven't thought about?


texts: Component / Entity-based design => no inheritance at all?

texts:
[I understand that this this could be seen as a rather theoretical question, but I think it has real-application impact].

"Academic" base
With a component-based design one wants to get rid of the long inheritance chains known in larger games ("deadly diamond of death"). So we create a BaseComponent class that handles all the administrative chores (ID and type handling, possibly a generic list of properties, ...).

Now each actual Componentshould inherit from that base [start of academic/dogmatic flair] and only that base [end].

Concrete situation/example:
Assume I have three components with different attributes:

Person: age, name, gender, isTired, isSick, ...
Guest: satisfaction, desires, ...
Employee: current duty, shift end, ...

Now in traditional OOP design, Person would act as the base class for the other two. As I currently "forbid" that type of inheritance for the components in my project, everytime I am e.g. processing my employees and checking/updating their state attributes I have to either use some helper function to access the sibling component Person (if it exists) or send a message out that hopefully Person will be registered for and will process. Or I can simply assume that each Guest and Employee always will have the component Person. But then I might as well let those two components inherit from Person, so they for example both have the member functions to manipulate some specific properties.

Note: There will never be an Entity that has the component Employee, but not component Person (same applies to Guest). They are a fix requirement, which is why I am considering inheritance here at all.

Question:
My question is now whether anyone can see any real-life problems that would be introduced by (re-)incorporating a bit of inheritance into my components other than to a degree violating the original base/dogmatic concept and the risk that (if used excessively) I would end up with the exact same problem the component-based design tried to solve in the first place?

References:
Thread that ultimately led my to asking that question, showing such inheritance.


texts: Create Mesh in gap between tiles (in Unity3D)

texts:
I am loading two kinds of tiles (meshes in tile format) in Unity, both are placed in the environment correctly but there is a gap between these two tiles (see the picture below).
I want to fill this gap automatically either through scripting or a shader. With scripting, there is an algorithm I thought of, but its first step is taking too much time.

Get each tile and get the outer edges of the mesh (it's taking too much time to calculate with each tile, as there are thousands of tiles)

Then raycast from the outer edges of the mesh and get intersection points of outer tiles

Take vertices and draw the mesh.

I get stuck in the first steps, as it's taking so much time to calculate the outer edges of a tile. Maybe there is a solution available in form of a shader that works in the gaps of two meshes?
Here is visual representation:


texts:
Been reading up on various methods in the XNA framework, and found this one.

I've done some Google searching, but I can't seem to find any information on how to use this particular method overload. Parameters 3-5 are easy enough to understand, since they are used in another overload, but I'm not so sure about the first two.

I'm fairly sure that the first parameter is the mipmap level we are setting data to, but the second one has me completely lost.

However, I'm not exactly sure what I should be passing in here. I know it can be a null object, or a valid Rectangle object, but I'm not sure whether it is being used to specify the size of the mipmap texture like this:

Or whether it is supposed to be its position and size inside the Texture2D object like this:

Can someone shed some light on this please, and maybe provide a parameter sample or two so I can better understand? (I'm one of those people that can spend 2 hours trying to understand a theory and make absolutely no progress, and get it in about 5 minutes after a few examples [or half dozen for more complex stuff])


texts: How do you time jump animation with uneven landing surface?

texts:
Say my player jumps off from a certain point on a 2D surface. Say my surface is uneven, and has varying y positions along the level, how would I then be able to time my jump animation accordingly?
(The issue being is that the animation might get cut off half way through, or vice versa - the animation would be already finished while the player is still jumping/landing)


texts: Why is it Important to have render targets with the same bit size?

texts:
I am currently thinking of what type of GBuffer I'll need for deferred shading, hence I tried also to document myself online about the most common ones and their format.

Most of the GBuffer that I've seen used the same bit size for each render target, leading also often to unused channels. However, as first guess for my GBuffer, on paper, I need two 24 bit targets and two 32 ones or three 24 and one 32.

I understand that having the same "size" each attachment can be aligned better, but practically speaking is it better to waste channels (or reserve them for future use) and having all the RTs of the same size or I should use just what needed? In the former case, why it is such advantage, will the 24 bit ones be padded to 32 anyway?


texts: Unity Custom EventManager, multiple arguments, and order

texts:
I have some hard question for me...
I have a nice EventManager, who handle multiple arguments. (no argument, one int, one bool, a GameObject and a bool... but for each sort, I have to create a special dictionnary for this...

public class EventManager : SingletonMono<EventManager>
{
        //here I have many, many class who handle all sorte of different arguments...
         private class UnityEventInt : UnityEvent<int>  {    }

        //here definition of all dictionnnary for each class...
        private Dictionary<GameData.Event, UnityEvent> eventDictionary;
        private Dictionary<GameData.Event, UnityEventInt> eventDictionaryInt;

    private void Awake()
    {
        Init();
    }
    void Init()
    {
        //here initialise all dictionnary
        if (eventDictionary == null)
            eventDictionary = new Dictionary<GameData.Event, UnityEvent>();
        if (eventDictionaryInt == null)
        eventDictionaryInt = new Dictionary<GameData.Event, UnityEventInt>();
        //...
    }

    //One of the startListening
    public static void StartListening(GameData.Event eventName, UnityAction<int> listener)
    {
        if (!Instance)
            return;

        UnityEventInt thisEvent = null;
        if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.AddListener(listener);
        }
        else
        {
            thisEvent = new UnityEventInt();
            thisEvent.AddListener(listener);
            Instance.eventDictionaryInt.Add(eventName, thisEvent);
        }
    }

    //one of the stop
    public static void StopListening(GameData.Event eventName, UnityAction listener)
    {
        if (EventManager.Instance == null)   //au cas ou on a déja supprimé l'eventManager
            return;
        UnityEvent thisEvent = null;
        //si on veut unregister et que la clé existe dans le dico..
        if (Instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.RemoveListener(listener);
        }
    }

    //and one of the trigger
    public static void TriggerEvent(GameData.Event eventName, int param1)
    {
        if (EventManager.Instance == null)   //au cas ou on a déja supprimé l'eventManager
            return;
        UnityEventInt thisEvent = null;
        if (Instance.eventDictionaryInt.TryGetValue(eventName, out thisEvent))
        {
            thisEvent.Invoke(param1);
        }
    }

And... when I want, in some script I do:

EventManager.StopListening(GameData.Event.PlayerAddScore, SomeFuncntion);
EventManager.StartListening(GameData.Event.PlayerAddScore, SomeFuncntion);

EventManager.TriggerEvent(GameData.Event.PlayerAddScore, 1);

here SomeFunction take 1 argument, but if i wanted to have 2... i have to hard code the case in my EventManager

So... My question is... how can I make that dynamic ? with only one Dictionary ? with only one list ? with good OOP or something ?

And secondly, how can I handle order or the call ?
Let's say 2 functions are listening for PlayerAddScore from 2 different script, how can I handle an order between the 2 function ?

Thanks you for help.


texts:
I am trying to play a movie file into an OpenGL texture in a Java application. I am using JOGL and have a basic OpenGL scene, but I have no idea how to play a movie into a texture.

The only thing I could find was this:

http://paulo.ragonha.me/blog/2008/08/java-movie-playback-jogl-fobs4jmf.html

It is quite old and uses JOGL 1.1 and Fobs4JMF, which is no longer maintained. I managed to get it to build in eclipse but it wasn't able to read my movie clip. I could probably convert the movie clip to an older codec to see if that works, but I would rather have a modern solution.

I am a professional game developer, so the OpenGL part is no problem, but I am new to Java (coming from a C++ background).

Is there any modern library that wraps this functionality in an easy to use package?


texts: AndEngine Moving a Connected Texture and Physics Body

texts:
In AndEngine, many times we create a TextureRegion for our sprite.  We can move this region around the scene but when I connect that region to a physics body I end up being able to use either one to move around.

My question is, which one do I move around.  Should I use the physics body's position or the Texture?


texts: Why am I running out of memory in D3DPOOL_DEFAULT?

texts:
When trying to using my company's D3D9 renderer and allocating everything in D3DPOOL_MANAGED I would run out of memory in the 32-bit process space.

I tried using our D3D9Ex renderer and allocating in D3DPOOL_DEFAULT, but that's giving me an error of 0x8876017C (D3DERR_OUTOFVIDEOMEMORY).

I'm unclear on what this means. Is this implying that the driver will not manage anything in D3DPOOL_DEFAULT?

I have 2.5GB of AGP space and 4GB of device memory, and all of my application meshes and textures are only 2.4GB on disk. I'm only using about half of those at any given time. Is there some hidden limit I'm bumping into here?


texts: Setting up OpenGL camera with off-center perspective

texts:
I'm using OpenGL ES (in iOS) and am struggling with setting up a viewport with an off-center distance point.

Consider a game where you have a character in the left hand side of the screen, and some controls alpha'd over the left-hand side.  The "main" part of the screen is on the right, but you still want to show whats in the view on the left.  However when the character moves "forward" you want the character to appear to be going "straight", or "up" on the device, and not heading on an angle to the point that is geographically at the mid-x position in the screen.

Here's the jist of how i set my viewport up where it is centered in the middle:

// setup the camera
    //

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    const GLfloat zNear = 0.1;
    const GLfloat zFar = 1000.0;
    const GLfloat fieldOfView = 90.0; // can definitely adjust this to see more/less of the scene

    GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
    CGRect rect;
    rect.origin = CGPointMake(0.0, 0.0);
    rect.size = CGSizeMake(backingWidth, backingHeight);
    glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar);

    glMatrixMode(GL_MODELVIEW);

    // rotate the whole scene by the tilt to face down on the dude
    const float tilt = 0.3f;
    const float yscale = 0.8f;
    const float zscale = -4.0f;
    glTranslatef(0.0, yscale, zscale);
    const int rotationMinDegree = 0;
    const int rotationMaxDegree = 180;

        glRotatef(tilt * (rotationMaxDegree - rotationMinDegree) / 2, 1.0f, 0.0f, 0.0f);

    glTranslatef(0, -yscale, -zscale);

    static float b = -25; //0;
    static float c = 0;

    // rotate by to face in the direction of the dude
    float a = RADIANS_TO_DEGREES(-atan2f(-gCamera.orientation.x, -gCamera.orientation.z));
    glRotatef(a, 0.0, 1.0, 0.0);

    // and move to where it is
    glTranslatef(-gCamera.pos.x, -gCamera.pos.y, -gCamera.pos.z);

    // draw the rest of the scene
    ...

I've tried a variety of things to make it appear as though "the dude" is off to the right:
- do a translate after the frustum to the x direction
- do a rotation after the frustum about the up/y-axis
- move the camera with a biased lean to the left of the dude

Nothing i do seems to produce good results, the dude will either look like he's stuck on an angle, or the whole scene will appear tilted.  I'm no OpenGL expert, so i'm hoping someone can suggest some ideas or tricks on how to "off-center" these model views in OpenGL.  Thanks!


texts: Determining how much of a tile is intersected by a ray to help calculate lighting and deal with shadow issues

texts:
I'm currently using the following steps for my lighting system

Calculate all the tiles along the perimeter based on the radius of the light
Cast a ray from the center of the light to each perimeter tile
The ray cast returns which cells it intersects
Each cell is lit based on their distance from the source (light attenuation)
If a cell is determined to be opaque then the subsequent cells are not lit (hard shadow)

The problem is that in some cases this makes the shadowing looks a bit odd and gives a Peter Pan type of effect where the shadow is not attached to the shadow caster (opaque cell).

For example:

The culprit is highlighted here:

If we take a look at the ray causing the issue we can see that it hardly intersects the cells behind the opaque object but they are still counted as being lit:

The method used for ray traversal is a typical Bresenham line drawing algorithm:

    while (true)
    {
        // Do not return cells outside the map bounds
        if (x0 < 0 || x0 >= width || y0 < 0 || y0 >= height)
            break;

        // Add the current cell to the list
        cells.Add(GetCell(x0, y0));

        if (MathExt.AlmostEquals(maxX, maxY, 0.01f))
        {
            // Cannot travel any further in this direction so this is the last cell
            if (x0 == x1 || y0 == y1)
                break;

            maxX += deltaX;
            maxY += deltaY;
            x0 += stepX;
            y0 += stepY;
        }
        else if (maxX < maxY)
        {
            // Cannot travel any further in this direction so this is the last cell
            if (x0 == x1)
                break;

            maxX += deltaX;
            x0 += stepX;
        }
        else
        {
            // Cannot travel any further in this direction so this is the last cell
            if (y0 == y1)
                break;

            maxY += deltaY;
            y0 += stepY;
        }
    }

My current line of thinking is to calculate how much of the cell is intersected by the ray and use that to influence the contribution of the lighting, alongside the attenuation.

Therefore, my question is how do I calculate how much of the cell is intersected by the ray?

Alternatively, can anyone suggest a more suitable solution for this issue?


texts: Manipulating Perlin noise output to create different ore veins in different depths

texts:
I am developing a simple project using Java, for Android. It is a side-scroller with a procedurally generated, infinite world. Most of the generation will be working on underground but I expect the same principles would apply to features that would be above the ground.
I have 2 coordinates. X goes Left-Right and Y goes Up-Down. I have managed to generate a density map using Perlin. What I do is looping through X and Y values, putting them in a noise function, and evaluating the resulting float to decide whether to place a specific tile or not. I have successfully created a uniform tile distribution. However I need something a bit more specialized.
You see, in order to make this interesting, I need to place various resources (Coal, Iron, Silver, Gold) as well as monster spawns in the map. I am thinking that it would be more realistic to place different resources in different depth levels. So for example, I need coal to appear between Y = -20 and Y = -50, Iron between -40 and -100, ogre spawners between -40 and -300 etc.
However, if I set these boundaries with a simple if statement like:
if (y<-20 && y>-50) {
    // Generate coal
    noise = perlin.getnoise(x,y,7);
    if (noise>=threshold) map.put(x,y,TILE_TYPE_COAL);
}
if (y<-40 && y>-100) {
    // Generate iron
    noise = perlin.getnoise(x,y,7);
    if (noise>=threshold) map.put(x,y,TILE_TYPE_IRON);
}

This generates sharp edges between those boundaries, like this:
http://imgur.com/wmllU5o
I need the noise to somehow generate resources that, when digging down, would gradually appear more often, and then gradually less so. Ease in and ease out.
For example, if I set the boundaries for coal to be between -20 and -50, most of the coal should appear in the middle of this ribbon, -35, while it should appear less in -20 and -50 levels. Perhaps I need a Gaussian distribution? I don't know where to start.
To put the question in a more mathematical form:
How do I manipulate the output of a Perlin noise function depending on one of the inputs (Y) in a non-abrupt, natural way, in order to gradually increase or decrease density for specific ranges of Y?
Thanks in advance


texts: I was wondering, is it possible to render a (3D) torus shape entirely in GLSL, i.e. without using vertex/index arrays? Suggestions are welcome, thanks.


texts:
I am working on a basic AI system to get an entity to follow a player. I created both the player and the ghost entity, but it seems as if the ghost only wants to increment both x and y, it never wants to do the opposite, or choose only x or y to use. Here is where I implemented the ghost and player in my constructor:

public MansionAzazel() {
    ...
    TileCoordinate ghostSpawn = new TileCoordinate(52, 50);
    TileCoordinate playerSpawn = new TileCoordinate(54, 52);
    player = new Player(playerSpawn.x(), playerSpawn.y(), key);
    player.init(level);
    ghost = new Ghost(ghostSpawn.x(), ghostSpawn.y(), player);
    ghost.init(level);
    ...
}

Here is the update() function for the ghost:

public void update() {
    int xa = 0, ya = 0;
    if (anim < 1000000)
        anim++;
    else
        anim = 0;

    if (player.getX() > xa)
        xa++;
    if (player.getX() < xa)
        xa--;
    if (player.getY() > ya)
        ya++;
    if (player.getY() < ya)
        ya--;

    if (xa != 0 || ya != 0) {
        move(xa, ya);
        walking = true;
    } else
        walking = false;
}

In which to sum it all up, the ghost entity will only and always move in one direction because the coordinates are 0 and I don't know why.


texts:
I'm having issues with lighting that I can't figure out, namely solid black sections. Any ideas?

Here's my fragment shader code:

#version 400 core

in vec2 pass_textureCoords;
in vec3 surfaceNormal;
in vec3 toLightVector;
in vec3 toCameraVector;

out vec4 out_Colour;

uniform sampler2D modelTexture;
uniform vec3 lightColour;
uniform float shineDamper;
uniform float reflectivity;

void main(void) {
    vec3 unitNormal = normalize(surfaceNormal);
    vec3 unitLightVector = normalize(toLightVector);

    float nDot1 = dot(unitNormal, unitLightVector);
    float brightness = max(nDot1,0.4);
    vec3 diffuse = brightness * lightColour;

    vec3 unitVectorToCamera = normalize(toCameraVector);
    vec3 lightDirection = -unitLightVector;
    vec3 reflectedLightDirection = reflect(lightDirection,unitNormal);

    float specularFactor = dot(reflectedLightDirection, unitVectorToCamera);
    specularFactor = max(specularFactor,0.0);
    float dampedFactor = pow(specularFactor,shineDamper);
    vec3 finalSpecular = dampedFactor * reflectivity * lightColour;

    vec4 textureColour = texture(modelTexture,pass_textureCoords);
    if(textureColour.a < 0.5) {
        discard;
    }

    out_Colour = vec4(diffuse,1.0) * textureColour + vec4(finalSpecular,1.0);
}

and vertex shader code:

#version 400 core

in vec3 position;
in vec2 textureCoords;
in vec3 normal;

out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;
out vec3 toCameraVector;

uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;

uniform float useFakeLighting;

void main(void) {
    vec4 worldPosition = transformationMatrix * vec4(position,1.0);
    gl_Position = projectionMatrix * viewMatrix * worldPosition;
    pass_textureCoords = textureCoords;

    vec3 actualNormal = normal;
    if (useFakeLighting > 0.5) {
        actualNormal = vec3(0.0,1.0,0.0);
    }

    surfaceNormal = (transformationMatrix * vec4(actualNormal,0.0)).xyz;
    toLightVector = lightPosition - worldPosition.xyz;
    toCameraVector = (inverse(viewMatrix) * vec4(0.0,0.0,0.0,1.0)).xyz - worldPosition.xyz;
}


texts: Difference in definitions of "Minkowski difference"

texts:
I'm trying to understand Minkwoski difference, as it relates to collision detection.

It seems, to me, that there are two definitions of Minkowski difference floating around. One, as defined by wikipedia and the other as defined for example here. My question is, am I wrong? Are those two definitions equivalent?

My intuition says no, because according to the Wikipedia definition, if B contains the origin  then B+c contains c, and that means that every such c must be contained in A. However, according to the other definition, A-B might contain points not in A.


texts:
The way I would texture a road within a given terrain is with a seperate mesh and a horizontally tileable texture such as this:

Then make sure the texture on the edge of the road and the terrain bordering the road looked kind of similar. That would however always create a visible seam such as in the image below taken from half life 2 episode 2:

Now the same game seems to blend in a horizontally tileable texture (the road) with a terrain made up of horizontally and vertically tileable textures (grass & dirt). How is this possible without a seperate mesh/material and without any visible seams, especially since the road is twisty meaning the texture has been rotated. I am completely baffled as to how this has been created, this is clearly beyond standard blend maps.


texts:
I am making a simple jump script by adding a separate script to the character.
I got the character from the Asset Store and I have left it untouched. I have searched the solution and similar problems to this, and I changed the force or JumpHeight to a pretty high value. But it is still nothing. The logs are printed out just fine.
public class JumpScript : MonoBehaviour {
public Rigidbody rb;
public float JumpHeight = 7.0f;

// Update is called once per frame
void Update () {
    if (Input.GetKeyDown (KeyCode.Space)) {
        Debug.Log ("PRESSSED");
        GetComponent<Rigidbody> ().AddForce (Vector3.up * JumpHeight);
        Debug.Log (GetComponent<Rigidbody> ());
    }
}


texts: How to determine the values of parameters controlling the game objects?

texts:
I am a C# developer and now trying to change to my dream field: Game Development.

I am new to Game Development and currently self learning Unity3D.

To me Unity is component based tools and we can set different parameters to control the behavior of the game object.

There's a question which kept me wonder for a long time:

Is there any "scientific" method to determine the value of the parameters of the component other than trial & error (brute force)?

Like when I watch some tutorials, the tutors normally will just tell you "change this value to x, change that to y" without tell you why is it so.

I just want to know how industry game developers set the value, is there a common standard, etc.


texts: Is there anyway to filtere a texture in glsl that turns stair like texels into smooth lines

texts:
I'm trying to filter a static, low resolution shadowmap. Unfortunatly, it doesn't look smooth, because of the way the default trilinear filtering works.

It does have a smooth transition from light to shadow, but you can still see pixelation in the texture. Now I am wondering if there are some techinques to hide these blocky texels with some custom filtering tricks, and make it look a bit more natural.

Imagine a low resolution texture with a  2 pixel wide, perfectly diagonal line. Now I'd like this texture to be rendered in a way that makes the line look like it was actual a high resolution line, by basicly filling all the hard edges between the background and the line with triangles facing towards the line, in order to make it look smoother.

Is there some custom filtering trick that allows me to make my shadowmaps look just a bit more anti-aliased?


texts: How to calculate the exit speed of ball bouncing off a solid surface

texts:
Hey all, I am working on a simple game to include some rigid body dynamics, involving placing (moving & rotating) some springs to bounce a falling ball into a target area.

My problem is correctly calculating the exit velocity of the ball after it hits the spring surface (Vexit, Ve for short)

Assume the following:
Initial ball velocity vector at point of impact is known (Vimpact, Vi for short)
Surface orientation vector is known (Vsurface, Vs for short)
Bounce coefficient (Bc for short) of ball after hitting surface is constant (for example |Ve| = 1.2 x |Vi|)

My algorithm is as follows:
-get surface normal vector, Vn
-get Vi inverse (reversing both x,y components to get reversed direction vector)
-get normalised Vi inverse, call this Vin
-get angle between Vin & Vn, by arccos(Vin . Vn). Let this be angle A
-rotate Vin by (2A) degrees to get normalised exit vector Ven
-Ve = Ven . Bc

Now as far as I can tell, this would work well. However, I am unable to know on whether to perform the rotation step in clock-wise, or anti-clock-wise motion; since the angle i get is always positive

What do you all think of this algorithm anyways?
Can anyone help me out on how to figure out the rotation direction?
Anyone have a better (faster,simpler,more accurate, etc) algorithm to use?

Thanks a lot!


texts:
I'm making a 2D game in which I create some textures dynamically for displaying as simple 2D quads. To achieve this, I call ID3D11Device::CreateTexture2D that requires a D3D11_TEXTURE2D_DESC.

typedef struct D3D11_TEXTURE2D_DESC {
  UINT             Width;
  UINT             Height;
  UINT             MipLevels;
  UINT             ArraySize;
  DXGI_FORMAT      Format;
  DXGI_SAMPLE_DESC SampleDesc;
  D3D11_USAGE      Usage;
  UINT             BindFlags;
  UINT             CPUAccessFlags;
  UINT             MiscFlags;
} D3D11_TEXTURE2D_DESC;

One of the fields is MipLevels. What I understand about this is that mipmaps consist of a collection of the same texture downscaled for better representation and performance of them when they are far away from the view camera.

Since what I'm making is a 2D game, I don't need this feature and I want to disable it. Is there any way to do so? At first, I thought I could just set miplevels parameter to 0, but then I read this:

  MipLevels Type: UINT The maximum number of mipmap levels in the
  texture. See the remarks in D3D11_TEX1D_SRV. Use 1 for a multisampled
  texture; or 0 to generate a full set of subtextures.

and:

  pInitialData [in] Type: const D3D11_SUBRESOURCE_DATA* A pointer to an
  array of D3D11_SUBRESOURCE_DATA structures that describe subresources
  for the 2D texture resource. Applications cannot specify NULL for
  pInitialData when creating IMMUTABLE resources (see D3D11_USAGE). If
  the resource is multisampled, pInitialData must be NULL because
  multisampled resources cannot be initialized with data when they are
  created.

This is what confuses me. I want to create an IMMUTABLE 2D texture (once it's dynamically generated at runtime it's not going to change anymore) plus I don't want any mipmap levels. How am I supposed to do this?


texts: Include a custom font when publishing in Visual Studio XNA

texts:
I have a custom font called "Gold Box Games" that I want to use in a game I'm making. I have the font installed on my computer and it works just fine in the program when I run it in test. However, when I examined the publish settings I noticed I could not include that font with the things the publish-created installer makes.

How do I include a custom font to be pushed along with the rest of my files built with the Publish Wizard? This font will also need to be installed when another user runs my program (installed during that first 'setup' phase when they run the game the first time.)


texts: `Awake` with [ExecuteAlways] sometime is not called in edit-mode

texts:
I'm trying to use the [ExecuteAlways]attribute to have a singleton both in edit- and -play modes. But the Awake() method sometimes is not called in the edit-mode. What could be the reason for this and how to fix it?

To make a short story long, I've got a not-so-new Unity project that I believe was developed before the age of ScriptableObjects, so they used MonoBehaviour to store game settings. And they used a kind of "Singleton" pattern that was not very stable and sometimes caused artefacts, such as creating an extra instance in edit mode which could often be saved with the scene accidentally and caused some other problems. The "Singleton" was written this way:

private static GlobalSettings instance = null;

public static GlobalSettings Instance
{
    get {
        if (instance == null)
        {
            instance = (GlobalSettings)FindObjectOfType(typeof(GlobalSettings));
            if (instance == null)
                instance = (new GameObject("GlobalSettings")).AddComponent<GlobalSettings>();
        }
        return instance;
    }
}

to fix it I've changed the code (and added the [ExecuteAlways] attribute):

[ExecuteAlways]
public class GlobalSettings : MonoBehaviour
{
    private static GlobalSettings _instance;
    public static GlobalSettings Instance => _instance;

    private void Awake()
    {
        if (_instance)
        {
            Destroy(this);
            throw new GameException($"The '{nameof(GlobalSettings)}' is a singleton!");
        }

        _instance = this;
    }
}

as I said Awake() is not called sometimes in edit-mode and the _instance remains null. Another problem is that even when Awake is called it happens after the first call of OnInspectorGUI() where the game settings are needed.

Any suggestions and considerations on how to make this code work stable are welcome!


texts: What are the semantics of glRotate and glTranslate's parameters?

texts:
I have been trying to play with OpenGL after watching some tutorials and I don't understand how the glTranslatef and glRotatef functions work. I believe a simple picture would help me.

I understand that glTranslatef changes the position of the "camera" (but does it change the position in wich the shapes are getting drawn)?

However, I don't understand the rotation concept at all. If I do glRotatef(1,0,0,1) it makes my quad spin around. If I just do glRotatef(1,0,0,0) it makes the quad smaller (further away) but if I try to rotate around the X or Y axis, I get a black screen. I don't understand the angle either. Help would be appreciated.


texts: Making particle bounce off a line with friction

texts:
So I'm making a game and I need a particle to bounce off a line. I've got this so far:

public static Vector2f Reflect(this Vector2f vec, Vector2f axis) //vec is velocity
    {
        Vector2f result = vec - 2f * axis * axis.Dot(vec);
        return result;
    }

Which works fine, but then I decided I wanted to be able to change the bounciness and friction of the bounce. I got bounciness down...

public static Vector2f Reflect(this Vector2f vec, Vector2f axis, float bounciness) //Bounciness goes from 0 to 1, 0 being not bouncy and 1 being perfectly bouncy
    {
        var reflect = (1 + bounciness); //2f

        Vector2f result = vec - reflect * axis * axis.Dot(vec);
        return result;
    }

But when I tried to add friction, everything went to hell and back...

public static Vector2f Reflect(this Vector2f vec, Vector2f axis, float bounciness, float friction) //Does not work at all!
    {
        var reflect = (1 + bounciness); //2f

        Vector2f subtract = reflect * axis * axis.Dot(vec);
        Vector2f subtract2 = axis * axis.Dot(vec);
        Vector2f result = vec - subtract;
        result -= axis.PerpendicularLeft() * subtract2.Length() * friction;
        return result;
    }

Any physics guys willing to help me out with this?

(if you're not sure what I mean with the friction of a bounce see this: http://www.metanetsoftware.com/technique/diagrams/A-1_particle_collision.swf)


texts: Unity Perspective Camera Width & Height In Visible World Units

texts:
I'm attempting to create 90 degrees top-down scenes where I'm working with a 4k or larger camera. What I'm trying to do is drop a script on the main camera and have a debug line that updates the main camera in [Execute Always] mode to tell me how many world units are visible to the camera width and height. For example, when dealing with a 1920x1080 camera I need to ensure 53.1876 width and 29.8704 units height are visible. When I switch the main camera to 5760x3420 I want to be able to ensure there are exactly 159.5628 units width and 89.6112 units height visible. The debug will allow me to change the camera's x value to increase or decrease altitude from game terrain or surface objects to achieve the desired number of visible world units width and height. I have tried to use ScreenToWorldPoint and ViewPortToWorldPoint but haven't been able to achieve desired results.

I was able to produce the desired effect with an Orthographic camera easily since the relationship of the orthographic size exactly corresponds to how many world units will be width and height when the aspect ratio is known such as the code example.

  var height = 2*Camera.main.orthographicSize;
  var width = height*Camera.main.aspect;

So I knew if I wanted a heights of 29.8704 I just had to make the orthographic size 14.9352.  I'm looking to replicate this with a perspective camera while understanding the differences in views.


texts: Playing animation on button press with a condition

texts:
I want to do menu animation. In the animator, its contain 2 animations. One is opening animation, the other is closing animation. I set the opening animation as default state and added condition between of them. The condition contains one parameter, it is a bool type parameter. I drag the script which controls they behaviours on gameobject and animator component, but when the opening animation plays and player clicks the play button the parameter turns into true but it doesn't play.

 Animator canvasAnim;

 public Button lvlSelector;
 Button lvlSelector_A;

 // Use this for initialization
 void Start () {
     canvasAnim = GetComponent<Animator>();

     lvlSelector_A = lvlSelector.GetComponent<Button>();
     lvlSelector_A.onClick.AddListener(LevelSelector);

 }
 IEnumerator SlideLevelSelectMenu()
 {

     yield return new WaitForSeconds(1f);
     SceneManager.LoadScene("LevelSelectMenu");
 }

 void LevelSelector()
 {
     canvasAnim.SetBool("clickedclose", true);
     StartCoroutine(SlideLevelSelectMenu());
 }


texts: What features should a moddable game have to make it easy to mod?

texts:
One of the objectives I have for a tactical RPG I'm making is moddability. My hope is that anything can be replaced with custom code.

For example: you can replace the combat system I did with, say, rules from other systems, like the combat system in tabeltop RPGs like d20 or Pathfinder (with enough perseverance, coding the whole thing), and just let the game use that, even though I'm not really sure how to go about designing my game to support that.

I don't have much experience with mods, save for trying out a few in Oblivion and Skyrim (*ahem* caliente, ENB mods, etc.).

So, to modders out there, what are the features that's there in easy-to-mod games that you like, that make you think "wow if this didn't exist, making my mod would have been almost impossible". Stuff that just isn't there in games where you have a bad modding experience?

To start off, here are my initial thoughts:

I'm thinking of adding a Lua interpreter in my game, giving various objects in the game script access.
Resources will be saved in text format (in JSON). For example, behaviour trees will be serialized in JSON text files that can be edited. An in-game visual editor will also be provided.
A mod manager for the game will likely be good also (like BOSS in Oblivion).
The idea of "mod packages" for easy distribution.


texts:
This seems easy but I can't figure it out, when I have one circle(c1) collide with another(c2) I give the c2 circle the heading of c1 and send the c1 circle on the normal vector to the heading (the heading is stored as vector = (cos(theta), sin(theta)) this is probably a bad solution). So this works great when c1 is colliding head-on with c2, however if c1 collides with it's tail into c2 then c2 takes the direction that c1 is facing which causes them to intersect each other. Any ideas of how I can "re-word" the heading vector so it's not dependent on theta (the angle that c1 is looking at in the cartesian plane)?

Here is an example:
Elastic Collision


texts:
I'm working on a grid based puzzle game involving tracks, and I'm having trouble finding a nice way to have users draw those tracks on the grid in a way is easily understood. For simplicity I had the idea to make the user draw tracks by dragging/drawing on the grid. I thought this was a nice way to do things, since both mouse and touch inputs could be handled in the same way.
As how I have designed the game right now, the only tracks that are possible are straight and 90 degree turns, which I believe is also referred to as a 4-connected grid. I have a limit of two track pieces that can exist on one tile. This way the game supports junctions and crossings, which are an important part of the puzzle design, but things remain relatively clear.
I have looked at other grid based games that involve tracks or track-like connections, but many do not support junctions and crossings (Like the awesome Cosmic Express, and in some capacity Flow Free by Big Duck Games).
A game I know of that does support this is Trainyard by Matt Rix. There, when your dragged path connects three (adjacent) grid cells, a track on cell number 2 is created that connects cell 1 with cell 3. I personally find this method quite clear, and this is the system that is in my game right now, but prototype play testers found it quite difficult to draw the shapes they wanted and they made a lot of errors in the process, which became frustrating.
I can't really think of any other way than how Trainyard does it, at least at the technical level. In the end to build a track you need to know which sides to connect, so by dragging you have to touch at least three cells. Perhaps you can make assumptions at certain points to make things more streamlined? Or perhaps it is just a matter of better visualization? If anyone has thoughts on the matter, I would be very interested to talk about it! :) If you know of other games that have players draw tracks that support junctions and crossings, I would be very interested to see how they are doing it.
I do recognize the fact that you might need to have had some experience playing games with this system, so for what it's worth: The free version of Trainyard called Trainyard Express is still available on Google Play. The iOS version is gone unfortunately. It's quite an old game and hasn't been updated very regularly.
Edit 1: Currently track build logic is as follows: When dragging starts (mouse down on area where grid is shown), I start keeping a list of tile coordinates that the mouse is touching. When, while dragging, a new cell is reached, that new cell coordinate is added to the list. When the list length is 3 or higher, the last three coordinates in the list are used to create a track. So, for example, when the list is ((0,0), (1,0), (1,1)), a track on (1,0) is created with a turn that connects (0,0) with (1,1). Then, when (1,2) is reached, a straight track on (1,1) is added that connects (1,0) with (1,2). Hope this clarifies, else I could add a graphic representation.
Edit 2: Some issues that arise when using pure Trainyard drawing system:

Wanting to draw a straight line going right, starting at (1,1), accidentally grazing over the edge entering (2,2) below, resulting in a turn from (1,1) to (2,2) on (2,1). Then correcting back onto the correct row, and reaching to (3,1), resulting in turn on (2,1) from (2,2) to (3,1).

While wanting to make a turn to connect (1,1) with (2,2) via (2,1), users often start drawing on (2,1), resulting in no track being drawn.


texts:
I've recently finished my first ever Unity game. The game runs okay in my end but two of my friends had issues with the game. They both have 144hz monitors and the issues are solved when they lower the refresh rate to 60Hz. The problems are that any object who has a velocity depending on Time.deltatime, it gets halved. Is there a way to fix this on code so that nobody has to reduce their refresh rate when playing?
Here is an example code of a snowball projectile's behaviour. The snowball usually stays alive for 3f seconds and that allows him to go across the whole screen but in 144hz runtime, the snowball goes really slow and it does not last enough to even get across the half of the screen.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Snowball : MonoBehaviour
{
    [SerializeField] private float speed = 20f;
    [SerializeField] private Rigidbody2D rb;
    [SerializeField] private GameObject impactEffect;

    // Start is called before the first frame update
    void Start()
    {

        Destroy(gameObject, 3f);
    }

    void Update()
    {
        rb.velocity = transform.right * speed * Time.deltaTime * 75;
    }

    void OnTriggerEnter2D(Collider2D hitInfo)
    {
        if(hitInfo.CompareTag("Player") || hitInfo.CompareTag("Enemy"))
        {
        Destroy(gameObject);
        Instantiate(impactEffect, transform.position, transform.rotation);
        }
    }
}

Here is my game if anyone is interested in further examination: itch.io link


texts: How would you go about rendering something like a line of coke more realistically, say with shaders?

texts:
Im currently developing an app, where it simulates the snorting of cocaine. Im using LibGdx in Java to do that, I have got the mechanics down, but what Im currently left with is this:

Im currently rendering 1000 particles, which is doable by my Huawei P8, which isnt really high end. Doesnt really look good though. Any recommendations or other approaches you would use?