texts: Shader to render objects with distance independent size

texts:
I am trying to find a way to render certain objects in my 3d scene without the effects of the perspective projection. E.g. I want them to have the same pixel dimension independent of distance to the camera or the dimensions of the viewport.

Here is what I tried in the vertex shader so far

uniform vec2 screen_size;

varying float camera_distance;

void main() {
    mat4 mvp = projectionMatrix * modelViewMatrix;

    float scaleFactor = 2.0 * 50.0 / screen_size.x;
    float w = (mvp * vec4(0.0, 0.0, 0.0, 1.0)).w;
    w = w * scaleFactor;

    gl_Position = mvp * vec4(position.xyz * w, 1.0);
}

So far no luck.


texts: Drawing texture with smaller size results in pixelated image, even after applying filter

texts:
Can someone please help me resolve this issue. I've tried searching myself and the common answer suggested is to use a TextureFilter. I've tried doing that multiple times but nothing works. My png resolution is 1024x1024, and I'm trying to shrink it's size to fit on screen. This is the kind of result I'm getting, you can see that the circle looks very pixelated, despite the actual image having anti-aliased edges.

[The original image is here.]

Here's the code:

    SpriteBatch batch;
    Texture img;
    Sprite sprite;

    @Override
    public void create () {
        batch = new SpriteBatch();

        img = new Texture("circle.png");
        img.setFilter(TextureFilter.Linear, TextureFilter.Linear);

        sprite = new Sprite();
        sprite.setRegion(img);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0,0,0,0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(img, 0, 0, 128, 128); //draw texture -- reduced size
        batch.draw(sprite, 200, 200, 128, 128); //draw sprite -- reduced size
        batch.draw(img, 250, 250); //draw texture -- original size
        batch.end();
    }


texts: Render error in xna DrawPrimitive for Assimp Mesh

texts:
I am trying to render the vertices of a scene with a cube I exported as an OBJ from Blender. The 8 vertices become 24 when imported into XNA but when I render it I dont see all faces. This is not an issue of missing meshes because I'm pretty sure this is being stored as the first and only mesh. I suspect this is because of the vectors defined in the Assimp Mesh object but I can't seem to find any help for this.

THIS IS SOLVED! The code shows how to render a 3D model using only Assimp and XNA with vertex and index buffers. oScene is the Scene object imported using Assimp. This code only draws faces in a single color without textures.

Here is the relevant code:

   private void SetUpVertices()
    {
        mMesh = oScene.Meshes[0];
        vertices = new VertexPositionColor[mMesh.VertexCount];
        indices = new  short[mMesh.FaceCount*3];

        int i=0;
        foreach (Vector3D mVec in mMesh.Vertices)
        {
            vertices[i] = new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red);
            i++;
        }

        int f = 0;
        Face mFace;
        for (i = 0 ; i < mMesh.FaceCount*3 ; i=i+3)
        {
            mFace = mMesh.Faces[f];
            f++;
            indices[i] = (short)mFace.Indices[0];
            indices[i + 1] = (short)mFace.Indices[1];
            indices[i + 2] = (short)mFace.Indices[2];

        }

        vertexBuffer = new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
        vertexBuffer.SetData(vertices);

        indexBuffer = new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None);
        indexBuffer.SetData(indices);

    }

    private void SetUpCamera()
    {
        cameraPos = new Vector3(0, 5, 9);
        viewMatrix = Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0));
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f);
    }

    protected override void Draw(GameTime gameTime)
    {
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
        effect = new BasicEffect(GraphicsDevice);
        effect.VertexColorEnabled = true;

        effect.View = viewMatrix;
        effect.Projection = projectionMatrix;
        effect.World = Matrix.Identity;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            device.SetVertexBuffer(vertexBuffer);
            device.Indices = indexBuffer;
            device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes[0].VertexCount, 0, mMesh.FaceCount);
        }

        base.Draw(gameTime);
    }


texts:
I have a Camera object that has the variables:

class Camera : Object
{
    public:
        float positionX, positionY, positionZ;
        float directionX, directionY, directionZ;
        int speed;
}

The positions are what I will draw my scene's position based on, the direction is a value between 0 and 1 that I will multiply for the speed to get the next position:

if(keyboardInput.GetKeyState(Key::ArrowUp) == KeyState::Pressed)
{
    _viewCamera.positionX = _viewCamera.directionX * _viewCamera.speed;
    _viewCamera.positionY = _viewCamera.directionY * _viewCamera.speed;
    _viewCamera.positionZ = _viewCamera.directionZ * _viewCamera.speed;
}

The problem is the rotation direction, which I'm calculating with:

if(mouseInput.GetButtonState(Button::RightButton) == ButtonState::Pressed)
{
    //Here I get how many pixels the mouse moved between the X and Y axis with mouse sensitivity accounted for
    float rotationX = mouseInput.GetMouseMoveX();
    float rotationY = mouseInput.GetMouseMoveY();

    _viewCamera.directionX = sin(rotationX * 3.1415/180);
    _viewCamera.directionY = sin(rotationY * 3.1415/180);

    _viewCamera.directionZ = cos(rotationX * 3.1415/180);
}

There is something missing here, but I can't get it right.
The direction when I'm looking to the left or right works fine, but when I look up or down I'm not taking into account the rotationY for calculating the Z direction.

This means, if I'm looking straightly down, I'm not supposed to move forward or backwards, just down along the Y axis. But I'm going forward/backward because I'm not calculating the rotationY in the directionZ.

I tried subtracting the cos(rotationY) to directionZ, but the movement didn't felt right (was pretty weird actually).

What's the proper math so I get the correct movement along all axis?


texts: How can I make a ball glow and cast light?

texts:
I want to make my ball glow and cast light on other objects in the scene.
The scene is generated at run time so I believe baking is out of the question.
Emission materials work only when the object casting the glow/light is static.


texts:
I'm working on a 2D game for windows phone where the player moves blocks around to bounce a laser beams.

I need to create some simple physics for moving the blocks.

For the moment I have a simple collision class, telling me if two rectangles collide. But that's not enough because when I'm moving a block the rectangle/rectangle function doesn't work.

By Doesn't work i mean,I manage the collision but I don't how to stop the block mooving while the user sliding the block.

The collision response for the block I want is if the user tries to slide it on another object, the block should slide up against the other object and not overlap.

How would I go about implementing this functionality?

Some code about how i impletement mooving block

{
            Currentposition = Station.Position;

            TouchPanelCapabilities touchCap = TouchPanel.GetCapabilities();
            if (touchCap.IsConnected)
            {
                TouchCollection touches = TouchPanel.GetState();
                if (touches.Count >= 1)
                {
                    Vector2 PositionTouch = touches[0].Position;
                    for (int i = 0; i < ListDragObj.Count(); i++)
                    {
                        if (ListDragObj[i].Shape.Contains((int)PositionTouch.X, (int)PositionTouch.Y))
                        {
                            ListDragObj[i].selected = true;
                        }
                        else
                        {
                            ListDragObj[i].selected = false;
                        }
                        ListDragObj[i].Update(PositionTouch);
                    }
                }
            }
        }


texts: How to delete the splash screen I accidentally added?

texts:
GameMaker allows you to display an splash screen different from the default.

For a moment I thought of using the ready method that you just click the button in the global settings of the game.

In the second following I added the splash screen, I changed my mind and decided to do it by the "manual" method: create a room, set the time and everything.

That way I could only make one splash screen for all platforms. Also, for windows, using the method ready, I can not set the time, in addition to what was said, that I have to add to other platforms.

I know that if I unchecked the option to display the splash screen, it will not display by itself, but if it has not disappeared, so the game opening default screen appears, it will be in the game assets ... That is, a useless file of almost half a megabyte.

I have rebooted the GameMaker, delete the directory splash screen, but nothing happened.

Tell me how to delete it so that the default splash screen appears in the game settings (on the windows tab).


texts: Unity3d app immediately goes to background after starting up on iOS

texts:
So the iOS build of my game started doing this today and I have no idea why. The only think I can think of is that I added this line :

Application.runInBackground = true;

but this should not force it to go to the background on startup. Other games run just fine on the phone. It's very unlikely that the game itself is using too much resources. It does not crash it just goes into the background and when you select it from there it stays on for like a second and then goes back. Has anyone experienced this before ?


texts: How do I handle user input with good class structure/architecture for an Android game?

texts:
How do I handle user input having "good" class structure and following normal game architecture*?(see below). At first I didn't think this question was Android specific, although, after seeing a great response in C++ I would appreciate some insight on this question using Android architecture.

Current way I handle input for my Android Game:

Created controller class that takes X,Y screen events and X,Y
character position and returns an int that represents a direction the
character should move.

Call the controller method in the game's
update.

Send that direction value to my character update.

Character's update calls move (which is also passed this value).

Basic switch statement determines the direction my character moves.

Getters and setters for the position of the character.(should
I have them for this direction also)

Is there a better way of handling input? This doesn't feel like the best way. Where does input fit in with class structure and game architecture?
I'm going to accept the C++ answer but I would really like to see a Java answer for Android in the future. :D


texts: How do mobile mmo's deal with the graphical resources?

texts: I'm am creating an MMO(probably won't be so massive), and was wondering how to deal with the graphical resources. Obviously, I can't have what could be possibly a few gigs of images and animations loaded up to the client, so I need another way of doing it. I have tried having a php webserver that updates itself and writes to a file that the client draws, however this seems slow. How can I speed up the process of updating the graphics while not having too much into the client?


texts: How to rotate the camera to point to a specified location?

texts:
I have a quaternion based camera class (which controls a view matrix) and would like a function to rotate the camera to face a specified point. The best approach I can come up with is that I rotate the camera on the plane of the two vector by the angle between them.

Any advice?


texts: Has a multi player graphic adventure* ever been made?

texts:
By graphic adventure, I mean point & click LucasArts-type games.
Those games have a mostly linear structure in nature, and usually don't offer as many variants as other games types like action, rpg, strategy, which makes this genre difficult to implement a multi-player feature.
I'd like to know if there has been any attempts on doing such a thing, and if it would be viable, as players going offline or leaving a game in the middle would affect significantly the other players' game.


texts:
I'm having trouble with key management. Movement works fine but the shooting does stuff that I don't want to happen.

Every time I press the arrow keys to shoot it works fine but when I press a key to move the shooting stops and then continues shooting in the direction that I'm pressing.

void Player::HandleEvents() {

    SDL_Event event;
    const Uint8* keyboard_state_array = SDL_GetKeyboardState(NULL);

    while (SDL_PollEvent(&event)) {
        switch (event.type) {
        case SDL_KEYDOWN:

            //Shooting
            if ((keyboard_state_array[SDL_SCANCODE_UP])) {
                shootDirectionY = -1;
            }
            else if ((keyboard_state_array[SDL_SCANCODE_DOWN])) {
                shootDirectionY = 1;
            }
            else if ((keyboard_state_array[SDL_SCANCODE_LEFT])) {
                shootDirectionX = -1;
            }
            else if ((keyboard_state_array[SDL_SCANCODE_RIGHT])) {
                shootDirectionX = 1;
            }

            //Movement
            //Horizontal and Vertical

            if (keyboard_state_array[SDL_SCANCODE_W]) {
                speedSenseX = 0;
                speedSenseY = -1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_S]) {
                speedSenseX = 0;
                speedSenseY = 1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_A]) {
                speedSenseX = -1;
                speedSenseY = 0;
            }
            else if (keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
                speedSenseY = 0;
            }

            //Diagonals and AD WS cases

            if (keyboard_state_array[SDL_SCANCODE_W] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
                speedSenseY = -1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_W] && keyboard_state_array[SDL_SCANCODE_A]) {
                speedSenseX = -1;
                speedSenseY = -1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_S] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
                speedSenseY = 1;
            }
            else if (keyboard_state_array[SDL_SCANCODE_S] && keyboard_state_array[SDL_SCANCODE_A]) {
                speedSenseX = -1;
                speedSenseY = 1;
            }
            if (keyboard_state_array[SDL_SCANCODE_S] && keyboard_state_array[SDL_SCANCODE_W]) {
                speedSenseX = 0;
                speedSenseY = 0;
            }
            else if (keyboard_state_array[SDL_SCANCODE_A] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 0;
                speedSenseY = 0;
            }
            break;

        case SDL_KEYUP:
            //Handeling speeds
            if (!keyboard_state_array[SDL_SCANCODE_W] && speedSenseY < 0) {
                speedSenseY = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_S] && speedSenseY > 0) {
                speedSenseY = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_A] && speedSenseX < 0) {
                speedSenseX = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_D] && speedSenseX > 0) {
                speedSenseX = 0;
            }
            if (!keyboard_state_array[SDL_SCANCODE_W] && keyboard_state_array[SDL_SCANCODE_S]) {
                speedSenseY = 1;
            }
            if (keyboard_state_array[SDL_SCANCODE_W] && !keyboard_state_array[SDL_SCANCODE_S]) {
                speedSenseY = -1;
            }
            if (!keyboard_state_array[SDL_SCANCODE_A] && keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = 1;
            }
            if (keyboard_state_array[SDL_SCANCODE_A] && !keyboard_state_array[SDL_SCANCODE_D]) {
                speedSenseX = -1;
            }

            break;
        }
    }
}


texts: How do you get main camera move along a specific route?

texts:
I've got a scene in the starting  of my project, and what I want to do is to get my main camera move along a specific direction and route.
Let's imagine I've got a 3-Dimensional array which contains The Positions of The points thereon. This is what I want to do :

1-Set the camera position on The first point and then go along with The other points, delay X milliseconds in each point and then go with the rest of it.

2-Whenever I will be able to change any of these parameters inside the script and programmatically:X,Y,Z components of The Position and Rotation of The Transform hierarchical property.

I'm sure enough trying to write an algorithm on my own would be a relatively difficult job, so please give me some tips and if possible a pseudo-code.
And finally I want this script to be launched at the beginning of the scene.


texts: What are the benefits of capping frames per second? (If any)

texts: I am working on a simple game in OpenGL, using SDL for display initialization and input, and it appears in terms of timing I have two options available to me. Number one being just sleeping for the optimalTimePerFrame - theTimeTakenToRender, when the optimalTimePerFrame in seconds = 1/theFramerateCap. (I'm not entirely sure if this is necessary, as it is equivalent to using vsync, which may be more accurate. If my assumption is correct then please tell me wheter or not SDL + OpenGL has vsync by default, and if not how to enable it.) The other is to measure the time since the last frame was rendered, and merely adjust movement accordingly. (The shorter time taken to render a frame, the less far entities move in that frame). In terms of performance, and decreasing flicker etc, what are the advantages and disadvantages of these two methods?


texts: Problem with revolving EP Curve in Maya 2012?

texts:
I am trying to create a animated butterfly i made this using the EP curve

but when i try to revolve this it turns out to be this

can anyone tell me what is the [roblem

Thanks

Akash


texts:
So I'm trying to add a "Rewarded video ad" with the reward being more time to play in the next game.
my RewardedAd.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Advertisements;
using UnityEngine.SceneManagement;

public class RewardedAd : MonoBehaviour
{
    public static RewardedAd singleton;

    private void Awake()
    {
        if (singleton == null)
        {
            singleton = this;
        }
        else if (singleton != this)
        {
            Destroy(gameObject);
        }
    }

    public void ShowRewardedAd()
    {
        if (Advertisement.IsReady("rewardedVideo"))
        {
            var options = new ShowOptions { resultCallback = HandleShowResult };
            Advertisement.Show("rewardedVideo", options);

        }
    }

    private void HandleShowResult(ShowResult result)
    {
        switch (result)
        {
            case ShowResult.Finished:
                Debug.Log("The ad was successfully shown.");
                StartCoroutine(NewGameWithTime());
                break;
            case ShowResult.Skipped:
                Debug.Log("The ad was skipped before reaching the end.");
                SceneManager.LoadScene(0);
                break;
            case ShowResult.Failed:
                Debug.LogError("The ad failed to be shown.");
                SceneManager.LoadScene(0);
                break;
        }
    }

    IEnumerator NewGameWithTime()
    {
        Debug.Log("NewGame Started");
        GameOverManager.singleton.GameOverAfterRewardAd();
        SceneManager.LoadScene(1);
        Timer.singleton.AddBonusTime(20);
        Debug.Log("NewGame Ended");
        yield return new WaitForSeconds(1);
    }
}

and my Timer.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;

public class Timer : MonoBehaviour
{
    public static Timer singleton;
    public Text timeTF;
    private float seconds = 10f;

    private void Awake()
    {

        if (singleton == null)
        {
            singleton = this;
        }
        else if (singleton != this)
        {
            Destroy(gameObject);
        }
    }
    private void Update()
    {
        if (seconds > 0f)
        {
            seconds -= Time.deltaTime;
            TimeSpan timeSpan = TimeSpan.FromSeconds(seconds);
            string timeLeft = string.Format("{0:D2}",timeSpan.Seconds);
            timeTF.text = timeLeft;
            TimeLeftCheck(seconds);
        }
    }

    public void AddBonusTime(float bonusTime)
    {
        seconds += bonusTime;
        Debug.Log("New Timer script:");
        Debug.Log(seconds);
    }

    private void TimeLeftCheck(float _time)
    {
        if (_time < 5)
        {
            //Debug.Log("RunningOutTime sound");
            //SoundManager.singleton.Sound_RunningOutofTime();
        }
        if (_time < 2)
        {
            //Debug.Log("Out of Time sound");
            //SoundManager.singleton.Sound_OutofTime();
        }
        if (_time < 1)
        {
            Debug.Log("Game Over");
            GameOverManager.singleton.GameOver();
        }
    }

The video ad is playing fine and it's resetting my ad counter in my game over manager but I can't seem to figure out how to start the next game with more time (20 seconds to so) but ONLY if they've watched the ad.

Also, I'm still learning so any suggestions or things I can improve, more than happy to take that criticism too!


texts: How can I call two functions in a sequence with onclick?

texts:
I'm learning Unity.

I have two functions, one that transitions to a new scene and the other one is the button animation.

I add both functions to the onclick of a given button. I assume it calls both functions at the same time and executes the transition without running the animation.

I want the button to run the animation first (I'm using DOTWEEN) and once it's done to execute the transition.


texts:
Using LibGDX + Box2D and my understanding of the answer posted from this question: Here

I apply the following impulse:

// modify sprite's Box2d Body object
int a = 8; // amplitude
int f = 1; // frequency
int p = 1; // phase
float value = (float) ( a * Math.sin( 2 * Math.PI *f * TimeUtils.millis() + p ) );
body.applyLinearImpulse( 0, value, body.getPosition().x, body.getPosition().y, false );

// render it
sprite.setPosition( body.getPosition().x, body.getPosition().y );
sprite.draw( spriteBatch );

But this just causes my sprite to go straight up and offscreen rather than doing a wave. What part of the algorithm am I doing wrong?


texts:
I want to implement custom preview for GraphViz files.

I created CustomEditor stub for that based on this beautiful gist: https://gist.github.com/prodigga/53ab658e1a818cd4ddfd#file-meshfilterpreview-part2-cs

using UnityEditor;
using UnityEngine;

/// <summary>
/// Inspector for .SVG assets
/// </summary>
[CustomEditor(typeof(DefaultAsset))]
public class GraphVizEditor : Editor
{
    public override bool HasPreviewGUI()
    {
        return true;
    }

    public override void OnPreviewGUI(Rect r, GUIStyle background)
    {
        var path = AssetDatabase.GetAssetPath(target);
        if (path.EndsWith(".gv"))
        {
            var texture = new Texture2D(1, 1);
            texture.SetPixel(1, 1, Color.green);
            GUI.DrawTexture(r, texture, ScaleMode.StretchToFill, false);
        }
    }
}

I expect to see green preview area, but preview keeps having gray background:

How to fix this and actually draw custom texture to a preview area?


texts: Creating a database with special items, like in Diablo

texts:
I am in the middle of creating a browser game. I need to add 'special items' like in Diablo, but simpler. Item names are fixed (e.g. 'ring of power'), so only their attributes change.

In my game there are different towns. Each town may trade a different set of items with randomized characteristics. For instance, in Town A a 'ring of power' will have better attributes than the same item in Town B (and, thus, it will cost more).

My question is how to construct the database to handle this.

After constructing the database I will create a small script that will assign a different subset of items in each town. Each item with random attributes and a price that reflects its value.

I can make the script; what I need help on is creating the database.


texts: Assigning sprite to a sorting layer through scripting

texts:
I have few prefabs with sprites which I want to assign to different sorting layers. How can I do it?
 I am also wondering if sorting layers matter if I use a perspective camera. Do they?


texts: How to add highlights or descriptions to the Unity Editor interface

texts:
Is there a way to develop a Unity learning program that runs within the Unity Editor?

For example, I want to create something like a highlight or a description on the Unity UI.


texts: How to combine embedded generated graphs in a finite 2D plane?

texts:
I'm pretty new to working with graphs but I'm looking at using them to create the world map for our game (a text mud with rooms/nodes and paths/edges between rooms). There are a number of interesting small-world generators, for example Watts-Strogatz (http://en.wikipedia.org/wiki/Watts_and_Strogatz_model) that I'd like to combine.

My question is how to combine different generators. All the rooms will have coordinates in an XY plane (the rooms themselves won't have real dimensions). I can easily generate a graph, and then laying it out I can work out the XY coordinates of its nodes. But then I'd like to generate a new graph and connect at least one of its nodes to a node on the previous graph.

My first idea is to figure out the XY bounding box of a graph, and use that to place it in the larger XY plane next to the previous graph (kind of tiling the graphs). Are there other methods I should be aware of?


texts:
I am developing game using libGDX libraries . I want to create multiplayer mode , where several players can play at the same time in the same room , each player can create his own room and other players can connect to the room they want , I thought a mechanism like this
In this mechanism the left client is the one who has created the room and other 3 clients are connected to that room . The game physics runs on the room creator and sends the positions of physical bodies to the server , server sends that positions to other clients , other 3 clients send their input to the server and the server sends that inputs to the room creator and that inputs influence on the physic. But I think this cycle is not good because if the device of room creator runs slow then the game will start lagging and the fps will drop down and other clients will see the game with the same fps which is in the creators device . So can anyone offer me another mechanism for multiplayer game? I am using Node.js for server-side program and Java for client side .


texts: Opengl in 500 lines barycentric calculation question

texts:
https://github.com/ssloy/tinyrenderer/wiki/Lesson-2-Triangle-rasterization-and-back-face-culling
I cannot figure out how we go from uAB-vector + vAC-vector + PA-vector = 0 to the linear system with those subscripts x and y? Is there another way of explaining how we take three vectors, split them into x and y type vectors, and produce a cross-product that can be used to find the barycentric coords (u, v, w)?
Also, I am not sure why there is a division by the z component of the cross product in last line of the barycentric function. Maybe the answer to my first question will make this more obvious.
Below is a picture of the section of the tutorial where I am stuck. Link to full page is above.


texts: Using USB sound input for an android game - is it possible?

texts:
We are brainstorming ideas for an app, for a major project using Android Studio, and writing in java. My major is game development, so I intend on trying to build a video game based off the use of an electric guitar, as input.

While I can set up a means to provide input via the audio-in, through the 3.5mm, having USB input would be far more effective.

My main question is: Is it feasible?

To give background, I believe it must be entirely possible, however, I am unsure how difficult the process would be.

I am basing my question off three things.

If I plug my Xbox controller directly into my phone, it automatically works. So the requirement for local support does not work as strictly as I understood it too.
If I plug the Rocksmith cable into a computer, and tell my sound card to "listen" to it, the guitar automatically comes through the speakers as if I was using the computer as an amplifier. This implies that no software is required on the computer side to interpret the input.
If you set up the electric guitar to connect to the computer via the microphone, it is not only compatible with Rocksmith, but it works just as well. This tells me the USB cable does not do anything fancy, in order to interpret the guitar - it must all be software side.

To start me off, all I really need to do is be able to interpret the frequencies. If I run into brick walls, further on, I will simply build around it, or change my games scope.

In terms of accessibility, I do understand the repercussions of requiring the Rocksmith cable to run the game. However, at the moment, simple being able to use the Rocksmith cable allows me to work on the part I am being marked on. If it goes to plan, I can access a more accessible means to use USB, later.

For those that are not familiar with Rocksmith, for the purpose of this question, it is simply a game that includes an electric guitar to USB cable, and is able to assess the player as they play the guitar, by reading its frequencies to determine what notes are being hit.


texts:
I try to find a success list among players for my project.
I thought If I find the winning probability of players , it would give me the success list in group.

I would like to give an example to explain in a score table.

Player A won Player B 2 times in 3 matches .
Player C won Player B 1 time in a match.
Player C won Player A 1 time in 4 matches.

My idea to find the winning probabilities:

p(Player X)=Total Winning number of Player X / Total Match Number

Thus we can calculate individual probabilities as above.

p(A)=5/8

p(B)=1/8

p(C)=2/8

The success list shows that
p(A)>p(C)>p(B)

If we get new player (Player D) and the new player gets a match with Player C. if Player D wins the match, we will get a new success list according to my formula above.

p(A)=5/9

p(B)=1/9

p(C)=2/9

p(D)=1/9

In last status: p(A)>p(C)>p(B)=p(D)

I do not feel that method is good enough because Player D won Player C but Player D is behind Player C. As a sense, I feel Player D must be more that Player C in the list.

And other disadvantages are

if a player do not make match so often ,it can go down in the list. For example , if Player A  do not make match for a while and Other players make matches,  Player A will go down in the list even if he has good winning rate among users. I feel my method does not give exact player power
If a player in middle of the success list makes so much match with a weak player, The middle player will get top in the list even the player is not good enough.

Please let me know your ideas and solutions . Which methods can be used to define for better success list? How did you solve that issues in your game project while preparing a success list for death matches.

Thanks


texts:
I wrote this code in the Load Content of XNA 4.0 for reading the star map, after actually adding it to my content, and I have no idea how to write/draw it onto my application, any suggestions?

    string starmap = null;

        using (var stream = TitleContainer.OpenStream("starmap.txt"))
        {
            using (var reader = new StreamReader(stream))
                starmap = reader.ReadToEnd();
        }


texts:
I have a top down RTS type of game where the player (God mode style) can click a tree to chop it. I'd like to shake the tree where the base of the tree (where the position marker is) moves the least and the top the most to simulate like it's being hit by an axe so it shows visual feedback. Any ideas on how to accomplish this? Not really sure where to start.

This would be in 3D.


texts: How do I hide the console window for my released MonoGame game?

texts:
I am just finishing up my first game for the One Game A Month challenge which I wrote with the current MonoGame framework in Xamarin for Windows. I built the program in release mode, but running the executable produces a console window besides the game window. The console stays empty unless I deliberately cause an error to be logged, say by removing a required resource.

How can I get rid of this extraneous console window?

I looked through the project settings, but saw nothing alluding to removing the console window...


texts: XNA spritebatch drawing to the centre of screen

texts:
I have bit of a silly problem.

Is is possible to use SpriteBatch.Draw() method to draw to the centre of screen using coords from the beginning of window (So resolution 800x600 would use 400;300) instead of coords from the beginning of the Game coordinates? Right now I'm doing calculations to keep the object in the centre of screen but I'm wondering if theres easier method how to solve this.

I tried googling, but either this hasn't been discussed anywhere or I'm using wrong keywords in search.

Thank you.


texts: Discrepancy in Box2D Flash applied impulse

texts:
I have two clients. Player A, and Player B. What Player B sees in his screen is a mirrored version of what Player A sees. This is a carrom game, hence the mirroring.
Does anyone know why even if I have the same Impulse calculated for both of the clients, sometimes the resulting actions is different? The only difference is that the angle for Player B's impulse is inverted. Below is the snippet of the force calculation
var angle = data.originId == ig.game.playerIndex ? data.angle : invertRadAngle(data.angle);
var dx = (this.striker.powerMult * data.powerDrag) * (ig.game.boardControl.size.x * Box2D.SCALE) * -Math.cos(angle);
var dy = (this.striker.powerMult * data.powerDrag) * (ig.game.boardControl.size.y * Box2D.SCALE) * -Math.sin(angle);
var force = new Box2D.Common.Math.b2Vec2(Math.round(dx * 100) / 100, Math.round(dy * 100) / 100);

this.striker.body.ApplyImpulse(force, this.striker.body.GetPosition());

Here's the function in charge of inverting the angle
function invertRadAngle(angle) {
    return angle + Math.PI;
}

I am using ImpactJS's version of Box2D, hence the difference in syntax, but it should be the same with vanilla Box2D Flash


texts: Efficient structure for representing a transform hierarchy

texts:
Can anyone suggest a memory efficient way to represent a tree of matrices, for example in a hierarchy model?

I'm particularly keen to preserve data locality, and I suspect a structure-of-arrays (matrices & indices to matrices) type approach might be suitable.

As well as many chained matrix computations, this structure will probably be copied around in memory a fair bit, so having contiguous storage would be a big bonus.


texts:
My character moves continuously forward with

rigidbody.velocity = v3Force * strength;

My Swipe script is based on a youtube tutorial from https://www.youtube.com/watch?v=9ZIHx09GevI

I just changed the end result with

rigidbody.AddForce(v2Force * strength1);

For Right Swipe and below for Left Swipe

rigidbody.AddForce(v1Force * strength1);

Here are the vForce variables :

var v1Force : Vector3 = -transform.right;
var v2Force : Vector3 = transform.right;
var v3Force : Vector3 = transform.forward;

The swipe works fine, but the result isn't what I'm aiming for because when I swipe left/right my character seems to be moving only one frame left/right. And then continues moving forward. When I disable the forward movement, the swipe works great and makes my character move right/left for a period of time, after I swipe.

My question is how do I reach this result(moving sideways more than just a frame) with my continuous forward movement enabled?


texts:
Is there any way to have better quality textures ?

I thought that creating huge textures will improve their quality in game, that's why I draw textures with 0.25f or 0.5f scale.

I understand that computer can't display 4 pixels in 1 screen pixel, but how people do to have beautiful sprites while zooming ? even on smartphones...

Hope you can help me.


texts: Is it possible to show vertex information in tables in VS2012 like in PIX?

texts: In PIX I was able to watch the objects' vertex data at different stages in tables, like before vertex shader, between vertex and pixel shaders, and so on. Can you see this in Visual Studio 2012 graphics debugger? I mean, you can see the data as a list of sorts, but it's impossible to get a good overview of that if you have more than like 3 vertices.


texts: How to find and modify specific entity or gameobject in Hybrid ECS?

texts:
I am rotating 3 cubes in Unity with Hybrid ECS and the code goes like this :

public class RoatateECS : MonoBehaviour {
    public float moveSpeed = 10f;
}

class RotateSystem : ComponentSystem {

struct RoadComponets {
    public Transform transform;
    public RoatateECS rotateECS;
}
protected override void OnUpdate() {
    foreach(var e in GetEntities<RoadComponets>()) {
           e.transform.Rotate(0f, e.rotateECS.moveSpeed, 0f);
        }

    }
}

Inside OnUpdate all three cubes are rotating, I want to rotate the second cube in the opposite direction but how would I find a specific cube and modify it ?


texts: Knob in DigitalOnScreenControl not moving. Why?

texts:
I have set up a DigitalOnScreenControl in my game but the knob does not move. The base and the knob are drawn on the screen but the latter doesn't move as per the AndEngine example here.

Here is a snippet of my code:

this.mDigitalOnScreenControl = new DigitalOnScreenControl(300, 300, ResourceManager.getCamera(), ResourceManager.joystickControlBase,
                ResourceManager.joystickControlKnob, 0.1f, ResourceManager.getActivity().getVertexBufferObjectManager(),
                new IOnScreenControlListener() {

            @Override
            public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX,
                    final float pValueY) {
                    Log.v(TAG, "onControlChange");
            }
        });

        final Sprite controlBase = this.mDigitalOnScreenControl.getControlBase();
        final Sprite knob = this.mDigitalOnScreenControl.getControlKnob();
        controlBase.setAlpha(0.5f);
        controlBase.setOffsetCenter(0, 0);
        controlBase.setScaleCenter(10, 10);
                    controlBase.setScale(1.25f);
        knob.setScale(1.25f);
        this.mDigitalOnScreenControl.refreshControlKnobPosition();
        ResourceManager.getEngine().getScene().attachChild(this.mDigitalOnScreenControl);

The mDigitalOnScreenControl is a DigitalOnScreenControl object defined previously. I use a ResourceManager class to obtain texture regions and other game resources such as the camera amongst others. Note: Since the base and the knob are drawn, the ITextureRegions returned by the ResourceManager are valid. When I execute the program, there are no errors in DDMS.

The knob just doesn't move. Does anybody have an idea?

Thank you!


texts: How can I stop startcoroutine when pressing once on the escape key?

texts:
I want like in games to pass over a cut scene or splash screen in this case. So the user can hit the escape key to pass it over.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Assertions.Must;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Splashes : UnityEngine.MonoBehaviour
{
    [Header("Splash Screen")]
    public bool useSplashScreen = true;
    public GameObject splashesContent;
    private List<Graphic> splashes = new List<Graphic>();
    public float splashStayDiration = 3f;
    public float splashCrossFadeTime = 1f;

    void Start()
    {

        if (!useSplashScreen || splashesContent.GetComponentsInChildren<Graphic>(true).Length <= 0) return;

        //if we use splash screens and we have splash screens
#region Get All Splashes
        //if you build on PC Standalone - you can uncomment this
        //foreach (var splash in splashesContent.GetComponentsInChildren<Graphic>(true).Where(splash => splash != splashesContent.GetComponent<Graphic>()))
        //{
        //    splashes.Add(splash);
        //}

        for (var i = 0; i < splashesContent.GetComponentsInChildren<Graphic>(true).Length; i++)
        {
            var splash = splashesContent.GetComponentsInChildren<Graphic>(true)[i];
            if (splash != splashesContent.GetComponent<Graphic>())
            {
                splashes.Add(splash);
            }
        }

#endregion

        //And starting playing splashes
        StartCoroutine(PlayAllSplashes());
    }

    private IEnumerator PlayAllSplashes()
    {
        //Enabling Splashes root transform
        if (!splashesContent.activeSelf) splashesContent.SetActive(true);

        //main loop for playing
        foreach (var t in splashes)
        {
            t.gameObject.SetActive(true);
            t.canvasRenderer.SetAlpha(0.0f);
            t.CrossFadeAlpha(1, splashCrossFadeTime, false);
            yield return new WaitForSeconds(splashStayDiration + splashCrossFadeTime);
            t.CrossFadeAlpha(0, splashCrossFadeTime, false);
            yield return new WaitForSeconds(splashCrossFadeTime);
            t.gameObject.SetActive(false);
        }

        //Smooth main menu enabling
        splashesContent.GetComponent<Graphic>().CrossFadeAlpha(0, 0.5f, false);
        yield return new WaitForSeconds(0.5f);
        splashesContent.gameObject.SetActive(false);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {

        }
    }

    public void ExitGame()
    {
        Application.Quit();
    }
}

This splash is showing up each time the game is running. So I want to give the player the chance to press escape key to pass over it.


texts: Getting position of a coordinate on the surface of a sphere

texts:
So I want to create a object B close to another object A, but I'm trying to avoid that A covers B:

I have thinking how to achieve that. Take a look of the following drawing:

I have been thinking in a solution in a math - geometry way before searching for some Unity3D function to solve the problem. I have realise A and B would be on the same surface if the camera is within a sphere with radius c-A. So I guess the solution can be related to get a point at a B at a distance A-B from A on the surface of the sphere with radius c-A. Does it has sense? Any other idea? How to do it with maths and Unity?


texts: Do I have to take aspect ratio into account, when computing a direction in View Space?

texts:
I read an article about implementing a Single-Pass Volume Renderer.

After thinking about it, I have a question, which concerns the provided GLSL code snippet of the Fragment Shader.

To calculate the ray direction, the author uses the FocalLength (distance of the projection plane from view point) as Z-component, and the fragment coordinates in NDC-space as xy component. This gives a vector pointing from the view point to the pixel on the projection plane which is computed. Obviously this direction is supposed to be in View Space, because it assumes 0,0,0 as view point and the ModelView Matrix is used to convert the direction to object-local space. But I am not sure if that is correct, because isn't it that in view space the projection window isn't necessarily normalized, but has a width of twice the aspect ratio? It gets normalized by applying the projection matrix (at least in Direct3D as far as i know). So if this is true, why does this work? Why he maps the x component of gl_FragCoord to [-1;1], when the leftmost pixel would have an x-coordinate of -aspectRatio in view space?


texts:
I've been trying to implement several camera movements for my application. So far yawing, rolling, strafing, walking has been working properly, but I can't get my pitching to work properly. If I continue pitching upwards, it doesn't rotate back 360 degree, and instead gets stuck looking at the top of the screen.

Here's my code for Camera class

class Camera
{
    float m[16];
    Vector dirForward, dirUp, dirRight;

    void loadCameraDirections()
    {
        glGetFloatv(GL_MODELVIEW_MATRIX, m);
        dirForward = Vector(m[2], m[6], m[10]).unitVector();
        dirUp = Vector(m[1], m[5], m[9]).unitVector();
        dirRight = Vector(m[0], m[4], m[8]).unitVector();
    }

public:
    Vector position;
    Vector lookAt;
    Vector up;

    Camera()
    {
        position = Vector(300, 0, 100);
        lookAt = Vector(0, 0, 100);
        up = Vector(0, 0, 1);
    }

    void rotatePitch(double rotationAngle)
    {
        glPushMatrix(); {
            glRotatef(rotationAngle, dirRight.x, dirRight.y, dirRight.z);
            loadCameraDirections();
        } glPopMatrix();

        lookAt = position.repositionBy(dirForward.reverseVector());
    }
}cam;

I call the gluLookAt funtion by-

gluLookAt(cam.position.x, cam.position.y, cam.position.z, cam.lookAt.x, cam.lookAt.y, cam.lookAt.z, cam.up.x, cam.up.y, cam.up.z);


texts:
We have Windows 10 2004 with new sdk, we have new nvidia drivers with support wddm 2.7 and Dx12U but I still can't understand - how it should help to developers write one code for all platforms?
I don't see any new D3D_FEATURE_LEVEL_12_2, I don't see any new feature to help developers write one code to xbox and pc. Developers still need to check if user has support for all new features as they did before. So what is changed? For me it looks like it was made only for non-tech users who will ask seller give him only GPU with Directx 12 Ultimate sticker and that's all.
Microsoft docs doesn't have any information about directx 12 ultimate, only some blog posts.


texts:
I'm just getting into coding up some 3d rendering apps and I'm considering taking the jump into interactivity. While developing I've learned about Euler angles, gimbal lock, quaternions, frustum, culling, vector matrices, (quad/oc)trees, etc. Haven't touched vertex buffers, textures, mipmapping, peripheral interfaces (other than mouse/keyboard), and general game engine components.

I imagine all of these terms, techniques, have evolved over time from early "Wolfenstein"  implementation, to Quake 3 implementation, to modern day id Tech 5 implementation (and everything in between.)

Seems like information like this would be valuable so I can rule out certain implementations of something because they've already been obsoleted by other newer and cooler things. Essentially looking to evolve my own skills, but on a fast track (instead of reading all the material and chronologically keeping track.)

Are there any good articles that layout the evolution of game development techniques?

Thanks,
Chenz

P.S. I'm not trying to avoid RTFM, just trying to only get the up-to-date information.


texts: How can i change the Camera component height in FirstPersonCharacter?

texts:
The player looks very short. I changed his scale to 2,2,2 but the camera is in the middle it's like the player head is in the middle and not near the top.

In the screenshot in the Hierarchy i have a FPSController and the FirstPersonCharacter with the Camera is child of it. The FPSController scale set to 2,2,2 like the two soldiers. But you can see when i'm getting closer to the soldiers it looks like i'm looking at them from the ground.

I need to move the camera only up somehow.

And this is the camera and the firstpersoncontroller before running the game:


texts:
How do I check which object was activated before the other?
Let's say that there's door to open. To open the door you need to press firstly the second button and then the first button...but not the other way around.

I have these scripts for now:

Switch script (it's on 2 objects that are switches and both objects have colliders with IsTrigger checked):

public var IsPressed : boolean = false;
public var triggered : boolean = false;

function OnTriggerEnter() { triggered= true; }
function OnTriggerExit()  { triggered= false;}

function Update()
{
    if (triggered && Input.GetKeyDown(KeyCode.JoystickButton1))
        IsPressed = true;
}

SwitchCheck script (it's on door that should be opened)

public var Switch1 : Switch;
public var Switch2 : Switch;

function Update()
{
    if (Switch1.IsPressed && Switch2.IsPressed)
    {
        Destroy (gameObject);
    }
}

EDIT:
Let me explain this in detail.
If Button1/ Switch1 is pressed, door opens to World1.(no Button2 needs to be pressed.)
If Button2 and then  Button1 is pressed, door opens to the World2.


texts: Does `SetResourceArray` copy the data into the GPU?

texts: I am trying to create multiple textures, and only several of them change every few frames. I don't want to have to copy in the whole array via SetResourceArray for just a few textures that change, which brings me to my quesiton: Does SetResourceArray copy the data into the GPU?


texts: Why does interactive cloth not appear in game view in unity5 Pro?

texts: I used interactive cloth fir flags in unity5 Pro version and it appears in scene view but does not appear in game view while playing. What can I do for that please somebody help me out?


texts: How to change Unity's display settings/resolution?

texts: Unity displays in poor quality on my computer (the software itself), I was wondering how to change resolution/display settings?


texts:
I wrote Opengl ES wrapper, and I want to know, when I should use

  GL_TRIANGLES, GL_TRIANGLES_FAN and GL_TRINAGLES_STRIP

I read difference from OpenGL Red Book, but still doesn't understand what kind of them and when I should use them.


texts: Car simulation, motor torque and brake torque combine problem

texts:
I am creating a custom wheel collider in Unity. Every thing is fine now (suspension, collision, friction) except one problem that i cant get my head over for last 3 weeks. So now i have a car (one wheel only), it stand on top of a hill, then i apply a brake torque enough to make it stand still, after that i apply a motor torque that less than max brake torque, my question is how the car behave?. In my opinion, that if sum of motor torque (roll down hill direction) and gravity torque(friction force * radius) greater than the max brake torque will cause the car to roll down hill, and it remain stand still if motor torque (roll up hill direction). I really need help!

So i have mT(motor torque), bT(max brake torque), fT(max ground torque), rT(residual torque)

if (|mT| > |bT|) {

    |rT| = |mT| - |bT|;

    if (|rT| > |fT|) {
        wheel spin up with sign(mT) * (|rT| - |fT|);
        ground force = sign(mT) * |fT| / radius;
    } else {
        wheel roll without slipping;
        ground force = mT / radius;
    }
} else {

    |rT| = |bT| - |mT|;

    if (|rT| > |fT|) {
         wheel slow down to 0 with -sign(omega) * (|rT| - |fT|);
         ground force = -sign(velocity) * |fT| / radius;
     } else {
         wheel roll without slipping;
         ground force = -sign(velocity) * (|bT| - sign(velocity) * mT) / radius;
     }
}

All torque sign are on top.


texts: Using a Windows forms Textbox control in an XNA game

texts: What I want to do is this: Use a standard Textbox control in an XNA game. This will be the only control used, and the game is designed in xna alone. I (for some reason) cannot get the game to "see" the System.Drawing assembly in the program. I have added the needed reference, but still nothing.


texts: Client-side Prediction and Reconciliation for movement

texts:
I've explored the concept of client-side prediction with reconciliation quite a bit and there's one thing that puzzles me a lot.

From what I've seen in most guides, the flow looks a bit like this:

T0. Client sends MOVE command and immediately simulates a predicted result.
T0. Server streams gamestate (server does not know about Client's MOVE command yet and thus the T0 gamestate does not contain results for it).
T3. Client receives gamestate T0 from the server. T0 does not contain any movement and thus Client is forced to reconcile with the Server gamestate.

This way, Client will have to reconcile with the Server every tick it receives because they will never agree. If Client would be delayed by ½RTT before predicting, Client and Server should agree most of the time, but that's an unwanted delay.

If the Client submits a tickstamp with each command sent, the server can apply those commands pasttime. But this would mean that the client is authorative because it can make the server reconcile with its commands. There's also an issue here where players with a high latency will be changing a relatively distant past on the server, potentially undoing/invalidating a lot of already streamed gamestates.

I suppose the Client could simply pretend that T3 is T0 (sync to a different server tick depending on how high the latency to Server is) but I don't know the effect of that when interacting with other non-predictable entities (such as other players). I guess the Client would take longer to reconcile with the correct Server gamestate because of the induced "tick latency".

Is there something I'm missing here? Which is the best way forward for a twitch gameplay competitive game? I.e. Air Hockey or similar.


texts: How can I use Unity AR without cloud services?

texts:
From what I've read so far, it looks like if I want to build AR apps with Unity, I need to use some kind of cloud service.

Is there a way to use AR without sharing my (and my users) data to some 3rd party? If so, how do I do this?


texts:
I'm new to game development can anyone show me how to render tiles which were only seen by the camera I cant seem to find straight answer in google.

The game is in 2D and im using tiled


texts:
I am getting the following error, even though the code runs through the Draw could twice and then it errors:

  XNA Framework HiDef profile does not support alpha blending or
  ColorWriteChannels when using rendertarget format Single.

The BlendState that I'm using is:

BlendState newBlendState = new BlendState()
{
    AlphaBlendFunction = BlendFunction.Add,
    AlphaSourceBlend = Blend.One,
    AlphaDestinationBlend = Blend.One,
    ColorBlendFunction = BlendFunction.Add,
    ColorSourceBlend = Blend.One,
    ColorDestinationBlend = Blend.One
};

I even set the SamplerStates to PointClamp before the actual draw is called:

device.DrawUserIndexedPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, domeVerts, 0, 1024, ib, 0, 1860);

I don't understand how it can run successfully twice, and then fail.  Any help would be greatly appreciated.

A screenshot of the problem:


texts: OpenGL ES 2.0: Picking Individual Polygon Sprites from within VBO

texts:
Say, I send 10 polygon pairs (one polygon pair == one 2d sprite == one rectangle == two triangles) into OpenGL ES 2.0 VBO. The 10 polygon pairs represent one animated 2D object consisting of 10 frames.

The 10 frames, of course, can not be rendered all at the same time, but will be rendered in particular order to make up smooth animation.

Would you have an advice, how to pick up proper polygon pair for rendering (4 vertices) inside Vertex Shader from the VBO?  Creating separate VBO for each frame would end up with thousands of VBOs, which is not the right way of doing it.

I use OpenGL ES 2.0, and VBOs for both Vertices and Indices.


texts:
How can I play a YouTube video in Unity if given the YouTube URL link? I am using 2019.4.13
Is there a way to open webpages?


texts: Changing the direction of a particle in libgdx java

texts: I have a particle the explodes upwards. This would work the way I want if the particle always hit the ground. However I want the particle to explode at a -90 degree angle if it hits a wall from the left to look like you just exploded the wall. Is there a way to rotate the particle emitter in any way? Any help is extremely appreciated.


texts:
What is the best way to create a rather dynamic upgrade system for a tower defence game?
I thought of two possibilities:

Create enums for stats and math operation (latter could be just a char as well), and use the following function:

Upgrade (Stat, Value, Operation);

Like:

Upgrade (STAT_HEALTH, 2, OP_MULT);

would double health.
(Using an entity system with each one having an ID) Every tower, and its possible upgrades, are different entities, so:

Upgrade(int id);

would upgrade the entity to entity of ID id. This one doesn't look very good for me, as it looks like a waste of memory. This also makes me think of a system using a tree of stats nodes to define their dependencies, but I'm not sure what to do exactly.

Just started learning about JSON so the information needed would be available through it.


texts: How to set the Y position of Camera to another object's y position, but only once, not continuously?

texts:
Essentially, I want to set the camera's Y position to another GameObject's Y position, but I only want to do this one. If you do

cam.transform.position = new Vector3(0, thing.transform.position.y, 0),

it will continuously update to that object's y. Even if I store the Y float in a variable and set the camera's y to that it still continuously updates. It is only supposed to happen once.


texts:
I have done tiled maps and tile sets quite often, but in a rather simplified way. My tile sets were linear images of the size (tile_width * num_tiles) * tile_height, so I could find an index easily by using val src_pos = (index * tile_width, 0).

But in reality, I've come to notice, tile sets are actually fully sized images of two dimensions. That has some advantages, clearly, it's easier to draw. So I wanted to support that. The problem would be just to turn the index to the right source position. Failed a bit, so I wanted to ask here.

I've had two ideas dealing with it:

Turn the index into two values with

src_x = index modulo num_tiles_x
src_y = index div num_tiles_y

which lead me to some quite weird results. The tiles are correctly cut, but they're the wrong ones for the position.

The other idea is to take the image and turn it into a 1D-tile set by cutting it up. But I am afraid that would not be an option, as I am using Textures.

How is this solved in 'professional' applications?


texts: Unity - How to Receive "Animator" on AnimationEvent

texts:
How to receive "Animator" by parameter on an Animation Event parameter?

Its possible?


texts: What is Java missing that might make it difficult to develop fully-featured 2D games?

texts: Without using any external libraries, does Java, including all officially supported APIs give you enough to develop fully-featured 2D games? The reason I ask is that I hear a lot of "bad-mouthing" about Java and game development, but I'm wondering if that is only in regard to intensive 3D games. Also reading up on some Java games there often appears to be external graphics or sound libraries involved that simply have a Java port. This makes me think it isn't possible.


texts: How to use .fbx for 2D animation in unity 2D

texts:
I am new to unity so please bear with me. I have come to know that for animations it is better to fbx format in unity rather than sprite sheets. I am using unity 5.2 and till now i created all my animations inside unity using sprite sheets. I have been looking at fbx and i cant seem to understand how to use the fbx model i imported in a 2d game? All tutorials are for 3D games. Once the fbx is imported , it creates a prefab with all animations in it.. but how to use them ..? Can someone point me to a good tutorial or so..

thanks


texts: Is it possible to make calculations in a Quake 3/Live hud?

texts:
I would like to add a new field to a Quake 3/Quake Live HUD that shows the following number:

min(health + armour, health * 3) * (1.5 if guard_rune else 1)

This is the amount of damage you can take before getting killed, btw.

Is this even possible?


texts: Are .sln / .csproj usefull for sharing the Unity project?

texts:
We are experiencing some problems with GIT and Unity. It occurs pretty often that file .sln / .csproj give us some trouble, so after searching for a while on the web I've found that maybe this files are not necessary to push. Someone have any feedback for this? https://gist.github.com/hw/1234398 There for example are included into the .gitignore, but I honestly don't know what this kind of files does.

Can I exclude they from my repo or this file are relevant for some references in my game?


texts: Doesn't Unity5 support Expression Bodied Properties?

texts:
I wrote the following line in Unity5 using C#:

private static float Width => 0.015f;

Unity complained about the following issue:

Unexpected symbol `=>' in class, struct, or interface member declaration

Doesn't Unity5 support Expression Bodied Properties(a new feature in C# 6.0)?

I am really lost here...


texts: Expandable 2d environment by spawning and controlling individual tiles

texts:
what is the best way to implement an environment that is "expandable" in every direction so that when the player moves in any direction a new row or column of tiles that can be manipulated individually is created,however as the player moves into the new created area whenever he decides to comeback, the tiles that disappeared by going off the screen are there when he comes back.

What I'm trying to do is make a new row if the player moves upwards or downwards, or make a new column if the player moves sideways. But I can control the individual tiles to make them change colors or place items. Then whenever the player advances and new tiles are created and others are moved off the screen if the player decides to come back to the area the item that was placed and color change is still there. Sorry if I'm not explaining my best, if you need a better explanation I'll be happy to give you one. Thank you.


texts: Problem using a CharacterController with a moving platform

texts:
My game has a wierd problem that I can reduce to the following minimal working example.

There is a box object with a component with the following method:
 void Update() {
     transform.position = Vector3.MoveTowards(transform.position, endPoint.position, speed*Time.deltaTime);
 }

It is just a platform moving towards a given point.

There is a capsule object which represents the player. It has a character controller. In some part of the game, it is a "child" of the box object. Without further additions, it just moves along with the box, which is the expected behavior for child objects. However, when I add to the capsule another component with the following method:
 void Update() {
     GetComponent<CharacterController>().Move(new Vector3(0, 0, 0));
 }

the capsule stops moving with the box (this Update method is a reduced form of my actual method, which also included keyboard input handling).
When I change the Update method of the box to FixedUpdate, again the capsule moves with the box as intended.
Why does this happen?


texts: Manage massive items game data in an Android Idle Game

texts:
I'm working on an Android Idle game, with many items that user can buy in each level, that each of them has more than 50 levels who can be updated by the user. Each item in each specific level can produce some value of a specific unit every second in the game.
Currently, I manage this massive game data (Not user's data) in the Dictionary data structure in code, that each item has an instance of Item class for the value. Item class has many properties like for example multidimensional arrays of levels data.
I initialize this dictionary each time user opens the game.

The problem is we want to balance the game, and it needs to change this massive data many times for test. with the current structure, it takes hours to edit data each time.

My question is, is that a better way to manage massive items game data to can be simply replaced for example by data from an excel's sheets in Unity?
Thanks.


texts: SetTextureOffset in meter per seconds speed

texts:
I have this code snippet that faking the tiling offset speed. Now i want to set the speed in terms of meter per seoconds. how to divide or multiply that i get a number which is meter per seconds:

public float scrollSpeed = 0.5f;

    Renderer rend;

    void Start()
    {
        rend = GetComponent<Renderer>();
    }

    // Update is called once per frame
    void Update()
    {
        //rend.material.SetTextureOffset("_MainTex", new Vector2(offset, 0));
        //rend.material.SetTextureOffset("_NormalMap", new Vector2(offset, 0));

        float offset = Time.time * scrollSpeed * SpeedSliderController.globalSpeed;
        ChangeDetailTextureOffSet(rend.material, offset, 0f);
    }

    public void ChangeDetailTextureOffSet(Material Mat, float scaleX, float scaleY)
    {
        Mat.SetTextureOffset("_DetailAlbedoMap", new Vector2(scaleX, scaleY));
    }

Like how do i move 2 meter per seconds.?


texts: Love2D : How can I keep up with lots of small sprites' collision data?

texts:
So I'm using a SpriteBatch to keep up with lots of small pieces for a falling-piece puzzle game. I have an array of Quads (for different color blocks), and they are randomly added to the aforementioned SpriteBatch. Right now, the game determines when the current piece has hit the ground, then that piece is stopped and a new piece spawns that the player now can control.

In order to figure out when to stop dropping the piece, I need to do a collision check. This shouldn't be hard, because I should only have to check the falling piece (unless the current falling piece causes a chain reaction). But, what type of data structure should I use? I can't use the position data of the individual Quads, because the boundary boxes will actually be a different size/shape than the pieces (think triangle pieces, but I will need to use a slightly skinnier rectangle to fit upside-down pieces in between right-side up pieces).

Should I just duplicate the (x, y) pairs using offsets with a width and height, and store them in an array, or am I missing a more obvious/efficient way? I'm guessing that the play screen could fill up with several hundred of these pieces, and if I add two player mode, double that.

EDIT: Here's what the Quad size issue is all about:


texts: What is the meaning of this line algorithm?

texts:
I have been looking at codes of several open source 2d games and I have found this function.

GetLineCollisionHit(Vector2 Position1, int Width1, int Height1, Vector2 Position2, int Width2, int Height2)
    {
      int tile1X= Position1.X + Width1 / 16.0);
      int tile1Y= Position1.Y + Height1 / 16.0);
      int tile2X= Position2.X + Width2 / 16.0);
      int tile2Y= Position2.Y + Height2 / 16.0);
        do
        {
          int dx= Math.Abs(tile1X- tile2X);
          int dy= Math.Abs(tile1Y- tile2Y);
          if (tile1X== tile2X && tile2Y== tile1Y)
            return true;
          if (dx> dy)
          {
            if (tile1X< tile2X)
              ++tile1X;
            else
              --tile1X;
            (check collision)
          }
          else
          {
            if (tile1Y< tile2Y)
              ++tile1Y;
            else
              --tile1Y;
            (return true if collision)
          }
        }
        while (true);
        return false;
    }

What is really checking is if there is any collision of solid tiles between two points, for this look for the line between the two tiles. But I do not know if it is a coding problem since it is not implementing neither Bresenham's line algorithm nor DDA or similar. So what are you trying to find in this line dx>dy? What sense does it have to advance x while x > y since that way a line is not correctly created.


texts: Light Space and Light Texture Space in shaders

texts:
I'm looking into material translucency and I'm working through some GPU Gems documentation (http://http.developer.nvidia.com/GPUGems/gpugems_ch16.html).

In Example 16-4 it references matrices for both light space and light texture space.

   // Given a point in object space, lookup into depth textures
   // returns depth

   float trace(float3 P,
            uniform float4x4  lightTexMatrix, // to light texture space
            uniform float4x4  lightMatrix,    // to light space
            uniform sampler2D lightDepthTex)
{
  // transform point into light texture space
   float4 texCoord = mul(lightTexMatrix, float4(P, 1.0));

  // get distance from light at entry point
   float d_i = tex2Dproj(lightDepthTex, texCoord.xyw);

  // transform position to light space
   float4 Plight = mul(lightMatrix, float4(P, 1.0));

  // distance of this pixel from light (exit)
   float d_o = length(Plight);

  // calculate depth
   float s = d_o - d_i;

  return s;
}

Can anyone explain to me what light texture space iS and how exactly I'd calculate a matrix for it? I think I'm OK getting the light matrix and it's projection matrix but a 4x4 light texture space matrix is blowing my mind.

I can't find anything else that specifically references those terms, but I'm well aware that terminology for shaders changes depending on who you speak to. They may well be better known as something else, though I'd hope Nvidia would be using well recognised terminology.


texts: How to transition a coin to the middle of the screen then up when collecting it?

texts:
I have a coin sprite that animates spinning in place, like this.
When the player picks up the coin, I want to make a transition while keeping the animation. First moving towards middle, then much faster all the way up until it leaves the screen like this:

My question: Is this done mostly via adjusting the Transform component component via scripting? Or are games implementing something like this in a different way?


texts: Day/Night cycle with GLSL - blend from one colour to another along Sin curve

texts:
I am attempting to implement a day/night cycle using a GLSL fragment shader in a 2D game i'm developing in SFML. I am a novice with shaders with this one being my first.

Currently I am using a lightmap to achieve ambient lighting and spotlights from lightsources (e.g. campfire) which is working nicely. The lightmap shader I am using I got from following an old Alcovegames tutorial, see below:

uniform sampler2D texture;
uniform sampler2D lightmap;

uniform vec4 ambient;
uniform vec2 resolution;
uniform int theta;

float PI_180 = 3.141592653589793 / 180;

vec3 ToGlColour3(in vec3 colour)
{
    float dv = (1.0/255);
    return vec3
    (
        dv * colour.r,
        dv * colour.g,
        dv * colour.b
    );
}

vec4 ToGlColour4(in vec4 colour)
{
    return vec4
    (
        ToGlColour3(colour.rgb),
        (1.0/255) * colour.a
    );
}

void main()
{
    vec4 diffuse = texture2D(texture, gl_TexCoord[0].xy);

    vec2 lightcoord = (gl_FragCoord.xy / resolution.xy);
    vec4 light = texture2D(lightmap, lightcoord);

    vec4 ambientLight = ToGlColour4(ambient);

    float ambientIntensity = ambientLight.a * (sin(theta * PI_180) + 0.5);
    vec3 ambientColour = ambientLight.rgb * ambientIntensity;
    vec3 intensity = (ambientColour + light.rgb);

    vec3 result = diffuse.rgb * intensity;

    gl_FragColor = vec4(result, diffuse.a);
}

The ambientIntesity calculation is my attempt at cycling from night to day.
My issue is that it doesn't cycle bright enough to give an adequate daytime effect.

I was thinking I could use the current value of sine(theta) and interpolate from my ambient colour to white (representing fully lit daytime).

I'm just not sure how to achieve this in GLSL. Ideally a solution within GLSL would be possible to help develop my knowledge of shaders.

I appreciate any help, Thanks.


texts: Upper & Lower angular limits on Y and Z axes

texts:
My Task:
I'm trying to replicate this project. I'm using unity as my physics engine.
Currently I'm still learning how to work with the different joints unity has to offer. The type of movement I'm looking for is where a body is connected to only one other body and its relative movement can be limited based on angles on different axes.

My Problem: I'm using Configurable joints for my movement restrictions. The Low Angular X Limit and High Angular X Limit does exactly what I'm looking for since it can have a different uppper and lower rotation limit. Looking at the documentation, it seems that this can only be done on the X axis. The Y and Z axes only have a Angular Y Limit or Angular Z Limit which set the upper as the opposite of the lower limit.

My Question: Is it possible for the Y and Z axes to have the same lower-upper limit system that the X axis has? Is the use of configurable joint good for this task?

Thanks in advance :)


texts: Controlling roll rotation when travelling along bezier curves

texts:
I am currently working on a curve implementation for use in Unity which includes an editor:

The aim is to get an object to follow the path represented by the curve at a constant velocity. Currently you can place nodes in the curve and modify the weights of each node via handles to control the curve segments between nodes. The curve implementation is a standard Bezier curve.

It works as described except that sometimes the rotation of the object along the path is not great. For instance doing a vertical loop can cause the object to suddenly flip over at certain points. I am currently setting the rotation of the object as follows:

transform.LookAt(bezier(waypoints, handles, lookAhead));

This is computing the point in the curve slightly ahead of the current point and setting the object to "look at" that point. The pitch and yaw of the object will therefore be correct but the roll cannot be easily controlled.

I am currently trying to implement a way to control the roll as the object travels along the path but my maths skills are failing me once again. In the editor I am thinking of placing "roll" nodes along the path which represent the desired roll angle of the object when it reaches that node and interpolating between these nodes for the points in between. My questions are as follows:

How would you determine the yaw and pitch manually at each point? My objects are airplanes so they will always be facing "forward".
How would you know the direction to turn towards to get to the next nodes roll angle? It could be anticlockwise or clockwise I assume. Would I need to also add a control to say which way to turn?
How would I determine what is "up" to orientate myself when controlling the roll angle of the objects along the path?

EDIT:

Example: https://www.youtube.com/watch?v=0BHGoKOIQa0&feature=youtu.be

The linked youtube video shows the problem I am experiencing with using

 transform.LookAt(bezier(waypoints, handles, lookAhead));

alone to control the rotation Quaternion. Watch the plane object rotate when looping vertically. The box sticking out is on the top of the plane object.

When the object reaches the point when it should be "upside down" in the loop it spins quickly to be the facing upwards again. If I can make it so that the up vector of the object along the path follows the "natural" rotation along the curve I can then apply Quaternion control points to properly control rotation. Sorry if this is not entirely clear, I don't know the proper terminology for a lot of this stuff.


texts: An Object is moving but its velocity is 0

texts:
In Unity 5 I have an object move when I press a button, force is added as seen by the code below. Then once this force is added I print out its velocity. The problem is that in the console my first print out with the first button press is "velocity(0.0,0.0)" then the second button press gives the printout "velocity(2.0,0.0)". Why is it that i get a velocity of 0 on the first button press even though my object is moving on the screen?

if (isPressed == true) {
            moveableBarrel.GetComponent<Rigidbody2D> ().AddForce (new Vector2 (100, 0));

            Debug.Log ("velocity" + moveableBarrel.GetComponent<Rigidbody2D> ().velocity);

            isPressed = false;
        }

Edit **Incase anyone else asks, the code is within a FixedUpdate Method


texts: How do you disable frame skips in a game, in SFML preferably

texts:
by frame skip off i mean that the game should just slow down if the fps drops, just like in terraria, i got this code currently and want to implement it to it:
static class Globals
{
    static public Time dt = new Time();
    static public Vector2f Friction
    {
        get
        {
            return new Vector2f(2 * dt.AsSeconds(), 0);
        }
    }
}

class Player
{
        private void StartMoving(int _direction)
    {
        moving = true;
        direction = _direction;
        heldfor =  1;
        Move(direction);
    }
    public void Move(int _direction)
    {
        if(!moving)
        {
            StartMoving(_direction);
            return;
        }
        if(direction == _direction)
        {
            if(heldfor < heldforlimit) heldfor++;
            Velocity += new Vector2f(((speed * (heldfor / 10f)) * direction) * Globals.dt.AsSeconds(), 0);
        }
        else
        {

            direction = _direction;
            heldfor /= 2;
            Velocity = new Vector2f(Velocity.X / 1.5f, Velocity.Y);
            if (heldfor < heldforlimit) heldfor++;
            Velocity += new Vector2f(((speed * (heldfor / 10f)) * direction) * Globals.dt.AsSeconds(), 0);
        }

    }
    public void StopMoving()
    {
        moving = false;
        heldfor = 1;
    }

    public void Update(Time dt)
    {
        if(!moving)
        {
            if(Math.Abs(Velocity.X) - Globals.Friction.X < 0)
            {
                Velocity.X = 0;
            }
            else
            {   // i really should make this direction independent and apply direction at end of the update
                Velocity.X = Velocity.X > 0 ? Velocity.X - Globals.Friction.X : Velocity.X + Globals.Friction.X;
            }
            if (Math.Abs(Velocity.X) <= velocitySnapX) Velocity.X = 0;
            if (Math.Abs(Velocity.Y) <= velocitySnapY) Velocity.Y = 0;
        }
        if (Math.Abs(Velocity.X) > XMaxvel) Velocity.X = XMaxvel * direction;
        if (Math.Abs(Velocity.Y) > YMaxvel) Velocity.Y = YMaxvel * direction;
        Position += Velocity;
    }
}

class Program
{
    Player player = new Player();
    while(game.isrunning) // this is made up as the genuine code is too messy
    {
                    if (Keyboard.IsKeyPressed(Keyboard.Key.Right))
            {
                player.Move(1);
            }
            if (Keyboard.IsKeyPressed(Keyboard.Key.Left))
            {
                player.Move(-1);
            }
            window.Clear(Color.White);
            window.Draw(player);
            player.Update(Globals.dt);
            window.DispatchEvents();
            window.Display();
            window.SetView(mainview);
            Globals.dt = deltaclock.Restart();
    }
}


texts: Intersection of two limited planes (stripes)

texts:
Have two limited planes. That means just squares or stripe in 3D space (or two connected triangles on the same plane).
What I want to know is exactly how (and whether) they collide.
My first approach would be to assume endless planes and calculate the collision line (which is always endless and exists unless the planes are parallel). However the resulting line just changes my problem to: "find the intersection of a line and a limited plane" and again I cannot think of a direct solution...
Anyone having a hint or an approach to a solution?
If it simplifies things, it would be safe to assume the planes to be limited in only one direction as in consisting of the area between two endless, parallel rays.
Huge thanks in advance!


texts: 3d world vertex translation to go to 2d screen coords

texts:
My technical english is a little rusty so to avoid misunderstands please be patient with me :)
I will try to be brief and clear

Situation:
- I have a 2d sprite character on the screen
- I've just start learning how to draw 3d primitives and work with the cameras
- I'm working on a 2d isometric environment
- I made a 3d isometric triangle which I want to center in character
- I'm trying to do something similar to a flashlight

Problem:
- The triangle is not centered on character (probably because of the scales between 2d and 3d workspace)
-the triangle speed does not match the character speed.

Code:

player vision

        playerVision = new VertexPositionColor[3];

        playerVision[0].Position = new Vector3(-15f, -30f, 0f);
        playerVision[0].Color = Color.Transparent;
        playerVision[1].Position = new Vector3(0f, 0f, 0f);
        playerVision[1].Color = new Color(70, 102, 25, 20);
        playerVision[2].Position = new Vector3(15f, -30f, 0f);
        playerVision[2].Color = Color.Transparent;

-

private void SetUpCamera()
{
    // isometric angle is 35º , for 50y = -107z
    viewMatrix = Matrix.CreateLookAt(new Vector3(0, -107, 50), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

    // TODO: use viewport for whole window or just the draw area ?
    projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GameInterface.vpWholeWindow.AspectRatio, 1.0f, 300.0f);
}

private void drawPlayerVision(GameTime gameTime, SpriteBatch spriteBatch, Vector2 playerDrawPos)
{
    // 50 is related with the camera position in the axis
    // TODO: this probably is incorrect since it should be a module of the distance? btw points
    Vector2 playerPos = playerDrawPos / 50;

    effect.CurrentTechnique = effect.Techniques["ColoredNoShading"];

    effect.Parameters["xView"].SetValue(viewMatrix);
    effect.Parameters["xProjection"].SetValue(projectionMatrix);

    // rotating like a radar
    Matrix worldMatrix = Matrix.CreateRotationZ(3 * visionAngle);

    // moving to the character
    worldMatrix *= Matrix.CreateTranslation(new Vector3(playerPos.X, playerPos.Y, 0));

    effect.Parameters["xWorld"].SetValue(worldMatrix);
    //effect.Parameters["xWorld"].SetValue(Matrix.Identity);

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
         pass.Apply();
         Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration);
    }
}

if you need more details please ask me
I've been trying to figure out  all by myself so its a little hard for me :)

Thank you for your assistance


texts: So I'm writing my first game which is a RTS and one of my main ideas for it is multiplayer deception however I'm finding it hard to control the scope of my project. Yes im thinking pretty small but because a key element of the game is multiplayer I'm wondering if its a good idea for a first game I know APIs such as appwarp exist and allow easier multiplayer integration but is this realistic for a first game or is it a better idea to go single player?


texts: How to Create a New Instance of a Game Object

texts:
Alright, please don't scald me here haha. I'm very new to XNA, C#, and game development as a whole. I have done web-design, but that is my main experience with programming. It is a Space Invaders type-ish game.

In the code below I have a Meteor class. In this class I want to create a meteor in a random location (on the X-axis) and then have it fall. I don't care much about it doing damage - yet.

I can always get one meteor created, and falling, yet when I press 'M' to create another instance of the class it isn't creating another meteor. I could very possibly be going about this entirely wrong...please forgive me if I am.

  class Meteor
   {

    private Random randomNumber = new Random();
    private Rectangle position;
    private int fallSpeed;
    private double damage;
    private int x, y = 0;
    private int WIDTH, HEIGHT;

    // List to hold meteors created (holds instance of Meteor class)
    List<Meteor> meteors = new List<Meteor>();

    // Texture for the meteor

    private Texture2D meteor;

    /// <summary>
    /// Create the meteor and each meteor's properties
    /// </summary>
    public Meteor()
    {
        HEIGHT = randomNumber.Next(0, 60);
        WIDTH = HEIGHT;
        fallSpeed = randomNumber.Next(0, 10);
        damage = fallSpeed * 2;
        x = randomNumber.Next(0, 600); // Randomly generates where meteor will spawn on X axis
    }

    public void createMeteor()
    {
        meteors.Add(new Meteor());
    }

    /// <summary>
    /// Load content (graphics) relating to the meteor
    /// </summary>
    public void LoadContent(ContentManager Content)
    {
        // Load meteor texture
        meteor = Content.Load<Texture2D>("Sprites/meteor");
    }

    /// <summary>
    /// Update the meteors position
    /// </summary>
    public void Update()
    {
        //Update position of metoer (falling)
        y++;

        // Testing purposes mostly...I want meteors to be created when I press 'M'
        if (Keyboard.GetState().IsKeyDown(Keys.M))
        {
            createMeteor();
        }
    }

    /// <summary>
    /// Draw the metoer (and it's new position).
    /// </summary>
    public void Draw(SpriteBatch spriteBatch)
    {
        position = new Rectangle(x, y, HEIGHT, WIDTH);
        spriteBatch.Draw(meteor, position, Color.White);

    }

    // So I can get the damage
    public double getDamage() { return damage; }
}
}


texts:
I am trying to build an infinite fog shader. This fog is applied on a 3D plane.
For the moment I have a Z-Depth Fog. And I encounter some issues.
As you can see in the screenshot, there are two views.
The green color is my 3D plane. The problem is in the red line. It seems that the this line depends of my camera which is not good because when I rotate my camera the line is affected by my camera position and rotation.

I don't know where does it comes from and how to have my fog limit not based on the camera position.

Shader

Pass {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform float4      _FogColor;
            uniform sampler2D   _CameraDepthTexture;
            float               _Depth;
            float               _DepthScale;

            struct v2f {
                float4 pos : SV_POSITION;
                float4 projection : TEXCOORD0;
                float4 screenPosition : TEXCOORD1;
            };

            v2f vert(appdata_base v) {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.projection = ComputeGrabScreenPos(o.pos);
                o.screenPosition = ComputeScreenPos(o.pos);
                return o;
            }
            sampler2D _GrabTexture;

            float4 frag(v2f IN) : COLOR {
                float3 uv = UNITY_PROJ_COORD(IN.projection);
                float depth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, uv));
                depth = LinearEyeDepth(depth);
                return saturate((depth - IN.screenPosition.w + _Depth) * _DepthScale);
            }
        ENDCG
    }

Next I want to rotate my Fog to have an Y-Depth Fog but I don't know how to achieve this effect.

It seems that this is caused by _CameraDepthTexture, that's why depth is calculated with the camera position.
But I don't know how to correct it... It seems that there is no way to get the depth from another point. Any idea ?

Here is another example. In green You can "see" the object and the blue line is for me the fog as it should be.


texts: How can I optimize a parallax effect consisting of multiple transparent layers?

texts:
I have a parallax effect in MonoGame consisting of multiple semi-transparent layers of textures. The effect is simple, but rendering multiple transparent layers on top of each other is rather slow. This effect doesn't need to be "accurate". How can I optimize this effect or fake it with shaders to make it more efficient?

The main premise is multiple full screen size semi-transparent layers drawn on top of each other from back to front. There are currently 3 layers + the actual game layer that also has some transparency.

I used a stencil buffer to render the game layer, already eliminating some of the parallax layers' pixels from rendering, but it's still inefficient.


texts: How does rendering with Swing compare to rendering with openGL?

texts:
[summary: Is the performance of Swing at least in the same dimension as openGL [through LWJGL]? If yes, what percentage would you give it? What  possible other problems can I expect from Swing in the long run, that I would avoid with openGL?]

So for quite some time I wanted to make my own simple java 2D game engine.

On my first try I was following a tutorial that used openGL (through LWJGL)
Because said tutorial wasn't complete I was kind of lost at the end, which caused me to use code that was so inefficient that a simple pong game crashed after 10 seconds because the jvm ran out of memory.

On my second try I, quite successfully, used Swing to render to a jPanel, which significantly reduced the complexity involved (Why can't lwjgl have ANYTHING similar to JPanel.render(Image)?) and allowed me to create some simple games that so far don't seem to take up excessive memory / cpu.

Now my question is whether this could bite me in the ass in the long run, or if it eventually only comes down to a negligible performance hit that I would trade for a more intutive way to code.
(Note that I don't care about 3D for now)


texts:
So, turned on my pc today thinking I we're gonna continue making my game but got denied by this error.

Have no idea how to fix it and why it's there at all, I haven't touched my project properties in days.

I start my game, he console pops up and just when I can see my games window blink it crashes and gives me this error :

  Unhandled exception at 0x0FE62707 (sfml-system-d-2.dll) in SFML_Game.exe: 0xC0000005: Access violation reading location 0xCCCCCCD8.

It crahes at the 2nd line of SFML code it goes trough, which is :

sf::RenderWindow window(sf::VideoMode(1200, 840), "SFML - Box2D Engine 1.0");

And the first line being this :

sf::Clock deltaClock;


texts: How to make a string[] from the words of a file in Unity?

texts:
I have .txt file containing all the English words separated by line breaks.

I want to turn them to a string[] so I can easily pick a random one from them.

The way I would do that in normal C# is the File.ReadAllLines(path) function in the System.IO namespace.

But, I don't think that I can use System.IO with Unity so the alternative that I could come up with is the TextAsset class which I can use to reference an imported text asset and get its text property as a string.

But, if I have a giant string how can I simply split it up into individual words and store them as a string[]?


texts: Are there recursive variants for trigonometric functions to potentially improve performance?

texts:
This is perhaps a better question for mathematics SE, however, this deals more with the performance side of gaming, and software in general. When I say recursive function, I mean recurrence relation.

I figure, in theory, a recursive function for sine, cosine, and tangent, would provide a function that takes less time to execute, rather than calculating the individual sine, cosine, and tangent every single time, considering that most functions in a game are continuous that require sine and cosine or tangent, e.g. the camera in a 2D or 3D scene. Whenever the mouse is moved, we could use a previous metric of sine, cosine, or tangent to calculate the next value.

Do such recursive functions exist? I have done a quick Google search, but I couldn't really find anything, and I would not know how to formulate a recursive function with my current knowledge of mathematics. (There must be a recursive formula for every function of x that is, at least, continuous.)

Were there older approaches taken in older or even recent video games to achieve good-enough results, like quaternion rotation, to achieve a real-time result?

Some examples where this might potentially be an optimization:

Any terrain generation algorithm. For example, Minecraft currently generates xyz 16-256-16 chunks. Instead of generating 16x16 or 16x256x16 chunks, you could generate individual blocks at a time as time passes or per tick. This would reduce the time per tick spent on generating terrain, and is relatively cheap as you could make it camera direction-dependent, e.g. generate blocks in the direction of the camera, and visible blocks can be generated first allowing lazy terrain generation. This would work with chunks of any size. The same could apply to vector terrain generation. However, relating to recurrence relation, said function would require (for Minecraft) one of 6 cardinal directions to calculate what the next block should be.
Camera matrices. Despite the fact that you can move your mouse around to make the camera jump on-screen, the Camera function is effectively contiguous per frame. When there is entropy, the transitions are very smooth with about the same interval for each camera rotation, and even then, all movement is a paraboloid shape. This could allow for some optimization like iterative approximation as mentioned in the comments.
Any algorithm that is inherently contiguous in software; interpolations; etc.


texts: Does every Windows Phone 8 device have one of a fixed set of resolutions?

texts:
Does every Windows Phone have one of the following 4 resolutions?
800x480, 1280x768, 1280x720, 1920x1080 pixels

Or is it possible that some devices only have a resolution of 1280x719 or 1279x720 pixel?

I use this code to determine the resolution of the device:

Resolution = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

But if I use the 720p and 1080p emulators, then I have the following results:

Resolution = Width:1279 Height:720

Why is the resolution width 1279 pixel and not 1280 pixel wide?

I get the same results with this code:

width = GraphicsDevice.PresentationParameters.BackBufferWidth;
height = GraphicsDevice.PresentationParameters.BackBufferHeight;

Is there a difference between GraphicsDevice.PresentationParameters.BackBufferWidth and GraphicsDevice.Viewport.Width? Which one should I use to determine the resolution of a Windows Phone device?


texts:
Let's assume I'm using this character.

(source: iconbug.com)
How would you implement collision detection for it? Using a bounding box doesn't seem to be a good approximation, because the bird's shape is nowhere near a square.
I was thinking of having a sort of quad tree data structure inside the object that represents portions of the image. Each leaf could be either false (in case it covers the white/transparent space outside the bird) or true (in case it represents an area of the bird i.e. beak, eye etc). Then somehow test the only obstacle in the scene for collision with the bird.
But my problems in my approach are:

I don't know how to initialize the quad tree.
Once the quad tree is initialized, I'm not sure how to traverse & use it once the obstacle is within the coordinates of the image.

How would you do collision detection with non-squarish characters?
LE: The other approach I've seen was to use multiple bounding boxes. For example I'd have one or a few bounding boxes for the beak, then a few of them for the hair or the tail. But it can get tedious. If this is a valid approach in my case, how would I generate those bounding boxes? I doubt I'd have to have them hardcoded in my program.
LE2: I care about fairly precise collisions. I can't imagine how a single bounding box or circle can at least approximate decently that shape, so this approach won't work.


texts: Converting a Google Sketchup file to 3DS?

texts:
I have a couple models that I've made or found in Google Sketchup, and I want to be able to use them in some programs I have that only support 3DS.  What is the best way to convert, without paying for Sketchup Pro?

Right now sketchup can export to .dae, so a .dae to 3ds would be just as helpful :)


texts: How do I implement friction in a billiards game?

texts:
I'm having trouble implementing friction in a billiards game.

Currently, the ball only slows on collision with the edges, but I also want some friction with the background.

How can I implement friction? (I'm using PhysicsJS.)


texts:
I'm working on a game a bit like "Super Smash Bros.", using C++ and SFML. I can't figure out a good way to program attacks.

First, I coded individual functions for each attack. The problem with this was that I needed three functions for each attack; one for dealing knock-back to other players, one for setting variables for the actual punch and one for checking for unique types of collision. This ends up being almost the same code for all the other attacks, and was also very messy for programming combos.

I then tried creating a class called Attack, and inherited classes like Punch and Kick. The problem with this was that I wasn't sure how to implement all of the methods in the Player class.

How do I program attacks and combos in a fighting game?