texts: Unity UpdateExternalTexture from MovieTexture windows crash

texts:
I'm trying to play a MovieTexture object with a SpriteRenderer object.
My code is working fine on OSX.

It crashes my windows 7 exported game, and play mode in Unity editor in windows 7.

I am sure the currentTexture.UpdateExternalTexture() call is making it crash, but I can't figure out why.

Can anybody explain why this is not working or how to debug it? The Unity log file didn't contain anything that seemed useful, just the message Crashed.

Here is what I am using

using UnityEngine;
using System.Collections;

public class FMAC_VideoPlayer : MonoBehaviour {

public string animationName = "escalator";

MovieTexture movieTexture;
Texture2D currentTexture;
SpriteRenderer spriteRenderer;
Sprite sprite;

void Start ()
{
    movieTexture = Resources.Load (animationName) as MovieTexture;

    currentTexture = new Texture2D(movieTexture.width, movieTexture.height);
    currentTexture.UpdateExternalTexture(movieTexture.GetNativeTexturePtr());

    spriteRenderer = GetComponent<SpriteRenderer> ();
    sprite = Sprite.Create (currentTexture, new Rect(Vector2.zero, new Vector2(movieTexture.width, movieTexture.height)), new Vector2(0.5f, 0.5f));
    spriteRenderer.sprite = sprite;

    movieTexture.Play();
}
}

Ideas?

Update

I have Debug.Log() ed the native texture pointer which prints the pointer address (ex. 556409680 ), so it does not seem to be NULL.


texts:
I am porting the IQM bone animation format to Javascript and have run into a problem...

The vertex shader is failing to compile and the only error message I get out is 'mat3x4' : syntax error on the first occurance of mat3x4 in the file.  Its the very data-type name itself that is unsupported, it seems.

This happens on all machines I have access to for testing, which have a variety of Intel and ATI cards and run Linux with Firefox.  (Chrome is not available.)

If I change all mat3x4 to, say, mat3 then my shader compiles fine.

does webGL support mat3x4?  (I can find nothing via Google)
how can I work around this?  How can I package the bones into mat4, for example, and keep the code working correctly?


texts: Rotating object around moving object/player in 2D

texts:
I am trying to implement a camera which rotates around the world around the player. I have found many solutions online to the task of rotating an object about the origin, or about an arbitrary point. The procedure seems to be to translate the point to be rotated about to the origin, perform the rotation, translate back, then draw. I have gotten this working for rotation around the origin as well as for a fixed point. Rotation of objects around the player works as well, provided the player does not move. However, if the objects are rotated around the player by some non-zero degree, if the player moves after the rotation it causes the rotated objects to move as well. I probably have done a poor job explaining this so here's an image:

And here's the code for the behavior:

renderx = (Ox - Px)*cos(camAngle) - (Oy - Py)*sin(camAngle) + Px;

rendery = (Ox - Px)*sin(camAngle) + (Oy - Py)*cos(camAngle) + Py;

Where (Ox,Oy) is the actual position of the object to be rotated and (Px,Py) is the actual position of the player. Any ideas? I am using C++ with SDL2.0.


texts: How can I selectively update XNA GameComponents?

texts:
I have a small 2D game I'm working on in XNA. So far, I have a player-controlled ship that operates on vector thrust and is terribly fun to spin around in circles. I've implemented this as a DrawableGameComponent and registered it with the game using game.Components.Add(this) in the Ship object constructor.

How can I implement features like pausing and a menu system with my current implementation? Is it possible to set certain GameComponents to not update?

Is this something for which I should even be using a DrawableGameComponent? If not, what are more appropriate uses for this?


texts: How does a 2D game like Zelda handle the character being behind buildings where only part of him is shown?

texts:
I'm trying to develop a simple Zelda-style game. I found this very useful topic

How did LoZ: A Link to the Past handle sub-tile collisions?

that I'm using as reference to develop my collision detection mechanism. However, there's something I've failed to understand. When Link is behind buildings, only part of him is shown. Can anyone please help me understanding how this effect can be achieved? Isn't the building part of the background?


texts: How to make a text of several letters animate, only with an animation

texts:
I wonder if it is possible to create an animation in a text with a single "animation". The problem is that for me to reach the desired effect I need to create an animation for each letter, as each one will appear a screen location. There is possibility to create this effect with just an animation? Remember that the deed is not the same as an animation into a sprite (one over another).

I did the animation for entering each letter on the screen, Curve > Transform > Position. (in the picture I tried to simulate using arrows to input source for each letter).


texts:
How do I make my ball bounce off objects on the screen? I'm having trouble detecting the collision, as well as calculating the response.

The picture below is a good example of how the program should be working once the ball runs into an obstacle

I made the ball bounce off the walls, but what's left is making it also bounce off of objects. Thanks for the help!

Here's the source code:

public class 2DGAME extends Application {

    public static Circle circle;
    public static Pane canvas;
    private long counter = 0;
    double X = 0;
    double Y = 0;

    @Override
    public void start(Stage primaryStage) {

        canvas = new Pane();
        Scene scene = new Scene(canvas, 800, 600);

        primaryStage.setTitle("2D Ball Game");
        primaryStage.setScene(scene);
        primaryStage.show();

        circle = new Circle(20, Color.BLUE);
        circle.relocate(100, 100);

        final Rectangle r = new Rectangle(20, 20, Color.DARKMAGENTA);
        r.setLayoutX(400);
        r.setLayoutY(300);

        canvas.getChildren().addAll(circle);
        canvas.getChildren().addAll(r);

        Timeline loop = new Timeline(new KeyFrame(Duration.millis(5), new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                if (counter++ % 5 == 0) {
                    // Moves the ball depending on the values of X and Y
                    circle.setLayoutX(circle.getLayoutX() + X);
                    circle.setLayoutY(circle.getLayoutY() + Y);

//Code to bounce off walls
                    final Bounds bounds = canvas.getBoundsInLocal();
                    boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
                    boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
                    boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
                    boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());

   //Bugged and not sure how to make it work
                    final Bounds rectangleBounds = r.getLayoutBounds();
                    boolean rectangle_left = circle.getLayoutX() <= (rectangleBounds.getMinX() + circle.getRadius());
                    boolean rectangle_right = circle.getLayoutX() >= (rectangleBounds.getMaxX() - circle.getRadius());

   //If the bottom or top wall has been touched, the ball reverses direction.
                    if (bottomWall || topWall) {

                        Y = Y * -1;
                    }
    // If the left or right wall has been touched, the ball reverses direction.
                    if (leftWall || rightWall) {
                        X = X * -1;
                    }

    //Bugged code for boucning off obstacle object
                    if (rectangle_left || rectangle_right) {
                       // X = X * - 1;
                    }

                }
            }

        }));

        loop.setCycleCount(Timeline.INDEFINITE);
        loop.play();
    }

    public static void main(String[] args) {
        launch(args);
    }

}


texts: How can i use draw gizmos to draw dots between each waypoints?

texts:
private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.blue;

        for (int i = 0; i < waypoints.Length; i++)
        {
            Gizmos.DrawLine(transform.position, target.position);
        }
    }

Before that i'm not sure how to draw at all between all the waypoints.

Instead line maybe to draw spheres or something else and scale it to dots/points ? And i also want to be able to set and change the number of dots/points between each two waypoints.

For example from waypoints[0] to waypoint[1] to draw 30 dots and from waypoints[1] to waypoints[2] 10 dots or just the same maount of dots between all waypoints.

For not not curves lines only straight lines like showing the path between the waypoints in game view.


texts: How to get an axe chopping animation to stop on collision with tree and smoothly go back to idle state?

texts:
Been stuck on this one for a few days.

I have an axe that moves around with the mouse.  When the mouse is in range of a tree, you can left click to start the axe swing animation.  Once the animation is complete, it goes back to the idle state in the Animation Controller.

The problem with the current solution is the axe can clip through the geometry of the tree.  I tried the 2 camera system (setting depth) to render the axe on top, but it didn't feel good.

The tree and axe has colliders on them.  The axe has a rigidbody.

I then tried another idea.  I disabled the animation controller for the axe on collision enter, and set the axe isKinematic to true.  This worked, the axe would not clip the tree, however, once I enabled the animation controller, the axe animation would continue to playing.  So I tried to switch the state back to idle and thought maybe cross fading would solve it, but it didn't work.

Is there a better way to do this?


texts: Why do Unity networking libraries fail when building for the Windows Store?

texts:
I am using Lidgren and RSA in my networking framework, but things like IPAddress are "nonexistent" when I try building for windows store. RSA classes don't work, either.

Why is this? How could I still have a networked game on the Windows Store?


texts: Error on new XNA 4.0 game project - No suitable graphics card found

texts:
Any ideas on how to fix this? According to what I remember about XNA 3 was that when running the application from scratch, I would get a blue colored windows with nothing rendered.

Any suggestions?

EDIT!

I right clicked the project and selected Properties and changed the Game Profile from Use HiDef to Use Reach. Now the familiar blue tint window is showing as expected.

What am I losing if I choose the limited API and why did I even have to choose this for it to work?


texts: Dashing mechanic in top down projectile dodging game in pygame

texts:
im making a simple third person top down game where you dodge projectiles than fly in from either side of the screen, its a simple high score game where the longer you avoid being hit, the better your score.
i want to give the player the ability to dash in any movable direction by using a resource (lets call it a dashcoin)
if the player collides with a certain target, they get one dashcoin, which can be expended to dash forward at increased speed for a brief moment. im also hoping to remove player control while they dash
this is the entirety of the code right now. currently theres no projectiles to dodge, but im working on that.
import pygame
pygame.init()

win = pygame.display.set_mode((630, 530))

pygame.display.set_caption("Cube Dash")

x = 250
y = 250
width = 30
height = 30
vel = 3

run = True
while run:
    pygame.time.delay(10)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and x > 60:
        x -= vel
    if keys[pygame.K_RIGHT] and x < 550:
        x += vel
    if keys[pygame.K_UP] and y > 10:
        y -= vel
    if keys[pygame.K_DOWN] and y < 490:
        y += vel
    if keys[pygame.K_ESCAPE]:
        run = False

    win.fill((0,0,0))
    pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
    pygame.display.update()

pygame.quit()```

im completely new to pygame and got most of this from tutorials, so any help is appreciated


texts: How to change from 60FPS to 30FPS while keeping things smooth?

texts:
Here is my current game loop:

final int ticksPerSecond = 60;
final int skipTicks = (1000 / ticksPerSecond);
float dt = 1f/ticksPerSecond;

while(System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){
        updateLogic();
        nextGameTick+=skipTicks;
        timeCorrection += (1000d/ticksPerSecond) % 1;
        nextGameTick+=timeCorrection;
        timeCorrection %=1;
        loops++;

On most devices I've tested my game on (this is an Android game BTW) it runs quite nice.

As you can see, I'm using a fixed time-step (defined as my ticks per second).

If I reduce my Ticks Per Second to 30, everything runs at the same speed but is nowhere near as smooth.  I keep hearing people say that 30fps should be OK for mobile games and everything should run great at 30 fps, but that's just not my experience.

Would be grateful if someone could give me some pointers on how to achieve this.


texts: How to put the output of one game into another?

texts: I want to add the screen of vrchat into a unity game environment so that I could play vrchat from a screen inside the unity environment. Is that possible? If not, why not?


texts: How can I properly render multiple layers/components in game?

texts:
I'm making a Love2D board game video game, which has multiple different components which need to be run and displayed on the screen at the same time. For example, I need to display the board, the characters, and the UI. Ideally, I would like to store each component in a seperate file (similar to Unix philosphy) In what way should I go about this?

My first idea was to create a screen/gamestate for each of these componenets, and stack them on top of each other so each is running/displaying at the same time. This feels like it's not a very proper solution so I'm open to other ideas.


texts:
I am trying to move a camera to the right, but it isn't moving.

i use this code to move:

Camera.Position.X = gameobject.transform.Position.X;

This is the camera code that i use to create Matrix3x2

        public Vector2 Position = new Vector2();

    float Rotation = 0;

    public float Zoom = 1;

    public Vector2 ViewportCenter { get { return new Vector2(ViewportWidth * 0.5f, ViewportHeight * 0.5f); } }

    public Matrix3x2 GetTransform3x2()
    {
        return Translation;
    }

    private Matrix3x2 Translation
    {
        get
        {
            return Matrix3x2.Translation(Position) *
                   Matrix3x2.Rotation(Rotation) *
                   Matrix3x2.Scaling(Zoom, Zoom) *
                   Matrix3x2.Translation(ViewportCenter);
        }
    }

This is the code that i use to render

        public void DrawGameobjects(Gameobject[] gameObjects)
    {
        RawMatrix3x2 CameraPosition = new RawMatrix3x2();

        foreach (Gameobject Gameobject in gameObjects)
        {
            if (Gameobject.Enabeld == true)
            {
                foreach (object Component in Gameobject.Components)
                {
                    //render 2D
                    if (Component is Sprite)
                    {
                        RawMatrix3x2 CurrentTransform = renderTarget.Transform;
                        Sprite NewSprite = Component as Sprite;
                            Bitmap Texture = Game.bitmapManager.GetTexture(NewSprite.texture.TexturePath);
                            RawRectangleF PositionRectangle = new Rectangle(new Point(0, 0), new Size(NewSprite.texture.TextureSize * Zoom)).ToRawRectangleF();
                            float Transparency = NewSprite.Transparency;
                            RawRectangleF ImageRectangle = new Rectangle(new Point(0, 0), new Size(NewSprite.texture.TextureSize * Zoom)).ToRawRectangleF();
                            Vector2 NewScale = (Vector2)Gameobject.transform.Scale;
                            Matrix3x2 Translation = Matrix3x2.Translation((Vector2)Gameobject.transform.Position);
                            Matrix3x2 Rotation = Matrix3x2.Rotation(Gameobject.transform.Rotation.X);
                            Matrix3x2 Scale = Matrix3x2.Scaling((Vector2)Gameobject.transform.Scale);
                            renderTarget.Transform = (Translation * Rotation * Scale).ToRawMatrix3x2();
                            renderTarget.DrawBitmap(Texture, PositionRectangle, Transparency, BitmapInterpolationMode.NearestNeighbor, ImageRectangle);
                            //renderTarget.Transform = CurrentTransform;

                    }

                    if (Component is Camera2D)
                    {
                        CameraPosition = (Component as Camera2D).GetTransform3x2().ToRawMatrix3x2();
                    }
                }
            }
        }

        renderTarget.Transform = CameraPosition;

    }

Everything moves except the camera


texts:
I'm trying to find or create a gravity well distortion shader for Unity. I've been looking around and all I can find are "lenses" which bend space around a black hole.

I'd rather have a distortion that "pulls" or "bends" the image behind into a small hole. Essentially, what this would look like if viewed from above (ignoring the sphere):

I can't seem to find any examples or a common terminology for it.


texts: Update and merge Unity coordinate systems multiplayer - Hololens

texts:
Project Summary

Creating a multiplayer HoloLens app that allows players to spawn and move objects around the local space they share.

Problem

I am able to connect to the other HoloLens and see the other player in the correct location but, for some reason the objects that I spawn I offset. I determined that the offset was based off of where the application started off. When developing in HoloLens the device always starts at (0,0,0). However, once the client has connected to the host and imported their world anchor the client's coordinate system is never updated event though the anchor is in the same physical location. This creates a problem because if the client is offset by 180 degrees everything that the host does is offset by the same amount when moving an object if that makes sense.

Moving toward a solution

After doing a lot of research I found this pertaining to sharing and HoloLens:

  "After a GameObject is locked via the LockObject call, it will have a WorldAnchor which will keep it in the same physical position in the world, but it may be at a different location in the Unity coordinate space than other users."

I found this on Microsoft's website here

https://developer.microsoft.com/en-us/windows/mixed-reality/shared_experiences_in_unity

Question

So obviously my question is basically, is there a way to update the x,y,z coordinates of (0,0,0) during runtime?


texts: Should I use a database to store ~10 000 names in a sports game?

texts:
I'm working on a single player sports game for a year or so and this doubt came up: how should I treat/store big amounts of data, like player names.
Let's take an arbitrary number as example: 10000 names, 5000 first names and 5000 surnames. These names would be equally divided between 100 countries, which give us 50 first names and 50 surnames per country.
Should I have a local database with these names (or even these countries) considering this data will be needed to generate new players names during the course of the game? Would that introduce limitations, considering I want to make my game moddable by players, as much as possible?
These doubts can be extended to other, more complex game entities, such as:

Players - each one with their own face, attributes, team etc...
Teams - each one with its own crest, kit, squad etc...

In my previous research about that, the SQLite popped up as a seemingly viable solution. It happens that I have almost no experience with DB's (specially in games) and would like to know if this is a good direction before start to study and try to implement it.


texts: How useful would it be to know a scripting language when developing an iOS game?

texts:
Possible Duplicate:
  Why do we use scripts in development?

I just starting learning iOS game development. I plan to make games using the cocos2d framework. While reading game dev related articles, blogs, books.. I've noticed scripting languages (such as Lua) are often used in game development. I'm wondering if it's worth taking the time to learn a scripting language. What's the role, usefulness of a scripting language in writing a game?


texts: Determine percentage of screen covered by an object without using frustum culling

texts:
On the CPU-side of an 3D first-person / ego perspective game I need to check whether what the players currently sees on screen is the inside of a box object defined by world space coordinates (the player might be outside of that box but on screen sees only/mostly the inside of the box, or vice-versa, looks from within the box to the outside).

The "casual" way of performing such a check would incorporate frustum culling but such an approach would be hard to achieve with my given set of engine parameters which I'd like to avoid if there is a simpler way.

What I actually have at the point where I would like to do the check (high-level script on CPU, not GPU side):

Camera world position
Camera direction
Camera FOV
Two Box corner world coordinates (left-bottom-front, right-top-back)

What I do not have right away:

View frustrum definition (near/far plane or say 6 planes defining
frustum)
Any specific pixel information (uv, view space position, depth or the
like)

What I would like to calculate:

Percentage of screen "covered" by box.

Any hints on how to perform such calculation?


texts: How to resolve push block physics in a 2D side scroller puzzle

texts:
I've been working on a 2D tile-based side scroller puzzle game in Unity with obstacles such as doors, keys, fans, portals, etc., but one type of obstacle, push blocks, is giving me some issues. Here is how it is supposed to work:

The player (an certain other obstacles) can push the block from either side, and it should move smoothly until it is either blocked by another obstacle or there is no ground beneath it
If it is pushed off an edge, it should fall into whatever hole is there, even if it is a snug fit. (left picture)
The top of the block should be flush with other blocks or surfaces when they are at the same level of height. There are no slopes in the tileset, so this would happen often. Motion across the combined surfaces should be smooth, with no way to wiggle between adjacent blocks. (right picture)
It must be able to respond to other forces in the game such as fans and gravity switches.

I have been using Unity's built-in physics engine, which has worked great for all other components of the game, but sometimes allows blocks to jump over holes, and sometimes blocks get stuck between other blocks when they shouldn't, so I have tried abandoning Unity's physics and made my own. It just made the rest of the game more glitchy and still failed to resolve the block problems.

If I change just the way the blocks physics work, I may be able to lock its position to a grid, where it cannot be left between tiles. That way I could get the more snug collisions to work. If I did this though, it would cause problems with the rest of the interactions. A floating block with a fan underneath it bounces around too much to be locked to a grid. Does anyone know a design that would allow all these requirements of be met?


texts: Unity 5 The Editor has stopped working Windows 7 64bit

texts:
As soon as I press the play button to attempt to run any of my updates games crashes the editor immediately and I can't run my games.

Does anyone know how I could debug this or where to start? Does Unity keep a log of errors when it crashes?

I have both a 2D and 3D game that do not work and the editor is not throwing any errors or telling me there are compile time issues.

EDIT: If it makes any difference it is the 64bit version and I am using a Student Pro License


texts: Is there a common way to execute a task at a certain pace, without relying on the task priority feature of the OS?

texts:
There is no cross platform way to set process priorities, and I don't want to use threads since there are no standard method of setting priority to certain threads, apart from the fact that threads are hard to use.

Let's say I have a task that takes a certain amount of computing time, which on my computer takes 10 seconds. This task usually takes a long time, like for example, loading geometry chunk dynamically, or opening a new audio ambience file. I don't need this task to be finished instantly because it's a big task so I can't afford to wait for a frame to finish, so I need to execute it over several frames, rather a certain amount of time.

Since I don't want to freeze the game, I can cut this loop into several batches and execute one batch per frame. If my game runs at 50 fps, a 10 second task can be divided in 500 batches. If my program loops over N*500 iterations, each batch loops over N iterations. If I don't want it impact others parts of my game, I can execute N/2 or even N/5 iterations per batch.

I'm not sure if I'm reinventing the wheel though, isn't there some C++ standard thing or programming pattern that allows me to do that already ? I'm not sure if it's optimal to cut a loop, and I'm not planning to use multithreading.


texts: How do I represent walls in a 2D tile based map?

texts:
I'm trying to create a simple 3D(2D) Dungeon Crawler but I am going to be using simple flat images to show the user they are in a "3D" world. Now what I mean is something like Sword and Serpents on the Nintendo.

Now as you can see on the right is a map, and on the left is the dungeon screen, I don't need help with the left screen no no. But on the right is the map, now I'm trying to think of a way I could represent this. I was thinking of using a 2D array, and doing something like this

w,w,w
h,o,o
w,w,w

So the H is the hero, and in front of him is two open spaces. so the hero can see two blocks around that is it. But if you look at the game, the player can move like this

h,o,o
o,o,o

so everywhere is open. but there is a wall between some blocks. Do you think an ID system would be better for example

1 = open space with walls on the north and south

2 = open space with walls only on the north

3 = open space with walls only on the south

etc, etc.

Do you think the ID system is way better or the use of W for a wall.


texts: Making isKinematic false when OnCollisionEnter()?

texts:
I have an issue with my script, I want to make rb.isKinematic go from true to false when collision is detected. With this script, nothing happens when a supposed collision is happening which means that rb.Kinematic = false does not work... The problem is that collision CANNOT be detected in the first place because rb.isKinematic is initially true (in my other script)! I checked this using Debug.Log to detect collisions. How can I fix this problem?

string lastTagCollided = "";
public Rigidbody rb;

void OnCollisionEnter(Collision col)
{
    if(col.gameObject.tag == "Pentagon" && lastTagCollided == "Pyramid")
    {
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = false;
    transform.DetachChildren();
    Destroy (GameObject.FindWithTag("Sphere"));
    }

if(col.gameObject.tag == "Pyramid" && lastTagCollided == "Pentagon")
{
    rb = GetComponent<Rigidbody>();
    rb.isKinematic = false;
    transform.DetachChildren();
    Destroy (GameObject.FindWithTag("Sphere"));
}

lastTagCollided = col.gameObject.tag;
}

My other script if you are curious:

void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Pyramid" || col.gameObject.tag == "Pentagon")
    {
        rb = GetComponent<Rigidbody>();
        rb.isKinematic = true;
        gameObject.transform.SetParent (col.gameObject.transform);
    }
}


texts: Animating a background 'pulse' with easing equation

texts:
I'm trying to find a suitable easing equation (or other method) to animate an object so that it 'pulses' (imagine a 'spike' on a music visualiser, or see the image I drew badly below)

'v' is the value I'm using to scale. 't1' and 't2' mark the end of a single pulse.

The game I'm working on is a puzzler, but I'd like to have objects in the background pulse in time with user-selected music.

I'm sure it's just a case of knowing what to search for, but any advice would be appreciated on how best to achieve this.


texts: Texture color change not working on custom effect

texts:
I'm new to custom effects (ex. pixel shaders) in monogame, but I've researched a bit and made some test effects.

I've noticed that the color variable "Color.[color]" doesn't change the color of the texture when an effect is active.

example:

I can't draw text that uses the effect, because the text doesn't turn black, it stays white.

This is my custom shader file:

sampler2D TextureSampler = sampler_state
{
    Texture = <Texture>;
};

float4 PixelShaderFunction(float4 pos : SV_POSITION, float4 color1 : COLOR0, float4 texCoord : TEXCOORD0) : SV_TARGET0
{
    float4 color = tex2D(TextureSampler, texCoord);

    float high = .6;
    float low = .4;

    if (color.r > high) color.r = 1;
    else if (color.r < low) color.r = 0;

    if (color.g > high) color.g = 1;
    else if (color.g < low) color.g = 0;

    if (color.b > high) color.b = 1;
    else if (color.b < low) color.b = 0;

    return color;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_4_0_level_9_1 PixelShaderFunction();
    }
}

And this is an example of the color change that doesn't happen:

spriteBatch.DrawString(font, [text], [position], Color.Black);

When the program starts (with the effect on), the text stays white and doesn't turn black. The effect works on all the other textures, when they don't need a color change.

Is this because of the sampler in the effect file?

EDIT

My question is actually if I can use the "Color.[color]" variable with a custom effect, or do I need to add a color parameter to the effect?

I ask this because I also have a button class that draws buttons with text on it. The draw function for the button draws the text and the button at almost the same time. color change for the text is written in that button class (ex. Color.Black). But when I use the custom shader, it doesn't work.

I'm also not sure if this will work with hlsl parameters for the colors, because I don't know how to seperate the button and the text with a hlsl shader, and only change the color of the text.


texts:
When I first created my code, there were quite a few cases where I would get horizontal and vertical gaps between tiles when displayed. I put this down to rounding issues with floats and just moved on to other things. Now that I've revisited the issue, I can't seem to get it working properly, even after trying my hardest to eliminate places where this sort of issue might happen. It seems to only happen when I place the camera at certain positions, which is why I think it's likely to be a float issue. If anyone could help me with the correct way to draw the tile layout, it'd be much appreciated.

This is my drawing method for the map:

public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    var topLeft = Camera.ScreenCoordinateToWorld(new Vector2(0, 0));
    // Readjust the position of the topLeft element so we get the actual
    // drawing position for the tile here
    topLeft = new WorldCoordinate(topLeft.X - 1, topLeft.Y - 1,
                                  -TileSize / 2, -TileSize / 2);
    var topLeftDrawPosition = topLeft.DrawPosition;
    var screenWidthInTiles = Game.GraphicsDevice.Viewport.Width / TileSize + 1;
    var screenHeightInTiles = Game.GraphicsDevice.Viewport.Height / TileSize + 1;

    for (var y = topLeft.Y; y <= topLeft.Y + screenHeightInTiles; y++)
    {
        for (var x = topLeft.X; x <= topLeft.X + screenWidthInTiles; x++)
        {
            if (x < 0 || y < 0 || y >= MapData.Count || x >= MapData[y].Count)
            {
                // Ignore out of range tiles to avoid exceptions
                continue;
            }

            var tile = MapData[y][x];
            var drawPosition = topLeftDrawPosition +
                               new Vector2((x - topLeft.X)*TileSize,
                                           (y - topLeft.Y)*TileSize);
            Tileset[tile].Draw(spriteBatch, drawPosition);
        }
    }

    base.Draw(gameTime, spriteBatch);
}

Broken:

Semi-working:


texts:
After the release of Minecraft I saw more and more rip offs of the game but some actually began to change it up a bit making the game have a organic look instead of the iconic blocky one that Minecraft does. If you'd like to look at the game that i'm referring to you can do so here. If you skip to around 50 seconds on the first video the steam page offers you can see the mining part that i'm wondering about.

I was wondering how this affect is achieved where they are able to remove part of the 3D object on collison with the players pick. I have heard about constructive solid geometry before and figured that could have been used but i'm not so sure.


texts: connecting multiple anti-aliased lines together

texts:
I implemented/copied the wu line algorithm from pseudo-code on wiki-pedia and other places.

When drawing a sine wave it breaks down at the point where the line changes from y dominant to x dominant (or vice versa). (I did not copy the endpoint code because it looks terrible and I do not need them for my purposes. )

Does anyone know a solution for this issue?  If not I will modify the algorithm myself to get it to work.  I am just curious if someone else has run into this and knows exactly how to fix it.  Is it possible to implement without the lines being globally aware of each other?  Or is this why drawing API's implement moveto and lineto functions?

The pseudo code


texts:
I am about to make a programming game for children, hence I will use blocks  (like Scratch or Stencyl). My question is: Is there a way that you can modify a script (let's say, by adding a string attached to a code block)?

Also, could there by a way to delete just some text for that script (for when I want to "reset" the script to its default state)?

Thanks in advance.


texts: Using shared memory instead of marshalling for C++ native plugins in Unity?

texts:
So I'm a C++ developer who has been playing with C# for a week or two in order to get acquainted with Unity, and I'm curious about the marshalling process used to transfer data for use in C++ native plugins. From what I can tell, the general consensus is that while using effective C++ plugins can be a performance increase for computation-heavy tasks, the marshalling process of transferring data can be significantly slower than the potential gains provided by the C++ flexibility.

I'm familiar with how shared memory works in C++ and it appears C# has the functionality required to use the buffers as well. From what I understand, the process of marshalling is slow due to copying, creating buffers and transferring chunks from one memory segment into another. Even though there's the problem of cache coherency when operating in shared memory, it may be less than the cost incurred by marshalling. I'm sure I'll have to do some experimenting.

Does anyone have thoughts or experience with using shared memory or marshalling in Unity who could weigh in on the question?


texts: Unknown variable direction in object.direction | Game Maker

texts:
This is my first question on a forum so please forgive any mistakes I may have made.

I am trying to make a game similar to the classic "Asteroids". I am trying to split the asteroids in two when a laser hits them. The following code is in an event in the asteroid object that is triggered when the laser collides with the asteroid.

inst1 = instance_create(x, y, medium1)
with (inst1) {
    speed = random_range(5,8)
    direction = laser.direction + random_range(0, 90)
}

inst2 = instance_create(x, y, medium1)
with (inst2) {
    speed = random_range(5,8)
    direction = laser.direction - random_range(0 ,90)
}

My issue occurs seemingly randomly. The game loads normally and the asteroids will split several times (sometimes 3-4, sometimes I can almost go through an entire game without encountering it) as I want them to, then this error pops up.

  ERROR in
  action number 1
  of Collision Event with object laser
  for object big1:

  Error in code at line 4:
         direction = laser.direction + random_range(0, 90)
              ^
  at position 26: Unknown variable direction

Any suggestions on how to fix this issue? Thank you very much in advance!


texts:
It's my first day using Unity, so be gentle :)

I've spent a good number of hours trying to find the solution to this problem that I'm having when trying to Build & Run my GearVR application in Unity.

I'm aware people have had similar issues, but most of the solutions seemed to boil down to duplicate .jar files in the project's assets folder -- something that I don't have after checking numerous times to make sure I'm not going insane.

So after getting the error message: "Unable to convert classes into dex format", I then get the following error output:

CommandInvokationFailure: Unable to convert classes into dex format.
C:\Program Files\Java\jdk1.8.0_60\bin\java.exe -Xmx2048M -Dcom.android.sdkmanager.toolsdir="C:/Users/MichaelAC/AppData/Local/Android/sdk\tools" -Dfile.encoding=UTF8 -jar "C:\Program Files\Unity\Editor\Data\PlaybackEngines\AndroidPlayer/Tools\sdktools.jar" -

stderr[
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/facebook/androidcompat/AndroidCompat;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/oculus/aidl/RemoteConstants;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/oculus/aidl/RemoteConstants$EntitlementResult;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/oculus/aidl/OVRServiceInterface;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/oculus/aidl/OVRServiceInterface$Stub;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/oculus/aidl/OVRServiceInterface$Stub$Proxy;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/facebook/sign/lib/FBSignVerify;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/facebook/sign/lib/FBSignSigner;
Uncaught translation error: java.lang.IllegalArgumentException: already added: Lcom/oculus/appmanager/vrsign/VRSignVerifier;

UNEXPECTED TOP-LEVEL EXCEPTION:
java.lang.RuntimeException: Translation has been interrupted
at com.android.dx.command.dexer.Main.processAllFiles(Main.java:608)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:311)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at SDKMain.main(SDKMain.java:129)
Caused by: java.lang.InterruptedException: Too many errors
at com.android.dx.command.dexer.Main.processAllFiles(Main.java:600)
... 9 more

Now, the only two jar files I have (that were included in the UnityIntegration package are vrlib & vrplatlib. As far as I can see, it seems to be vrplatlib that is causing the problem.

If I remove these two jar files (or even just vrplatlib) from the assets folder in my project, I get "Failed to build the APK. See console for more details" with even more error output.

Thanks for any & all help.


texts:
I'm using a Source Control Management tool (git) for backing up configurations, code etc. But how do I manage art assets and other game assets that are in binary formats, and tend to be big (animators, audio sources etc)?

The working theory is to backup all assets using cloud storage services like Google Drive or similar. But how do you effectively manage your projects? That would work for me being solo, but if I added another team member, how would I effectively manage projects while multiple developers/artists are contributing?

I'm working with Unity, if it's relevant.


texts: I've got an effect which is a fairly simple two-pass deal- but it involves rendering to a texture in the first pass. Is it possible to change the render target from within an effect? I would definitely appreciate the reduction in code duplication from C++ by being able to do both passes within HLSL.


texts: Rendering 3D out of layers - optimizing fillrate?

texts:
I'm rendering a city of several million cuboids that are all axis-aligned, touching each other and same-sized. They only differ in height.

Rendering them as real geometry is vertex-bound and too slow, so I've went with another approach: render them as several flat layers of a single, big texture. The more layers, the better the buildings look. This is similar to how a 3D printer works. Also I've seen it used for rendering hair, grass and snow. In my case, I'm using nearest-neighbor filtering to make the buildings square-shaped, and alpha-testing to control the building heights.

Here's a very zoomed-in screenshot so the individual layers are visible:

This works great, but when I use a higher number of layers, it gets too slow due to the fillrate. The cuboids are opaque so I tried optimizing this by enabling z-testing, but it hardly helped, because my shader is cheap (fixed-function, actually), and it's the only thing z-testing helps to skip. Or maybe it's because on my dev machine I have an Intel GPU and it doesn't do early-z discard.

So now I'm out of tricks. What could be used to optimize this? Also, any common names for the technique?

Notes:
- I'm aiming for OpenGL 1.4-level hardware, which is pretty restrictive when it comes to optimizing.
- I'm additionally using multitexturing with alpha-modulation to make arbitrarily-shaped, antialiased buildings (not enabled in the screenshot)
- Usually the city is viewed from a RTS-style viewpoint, all of it is visible, and it fills the screen, so fog or LOD techniques wouldn't work


texts: 2D character tips over sideways after collision with platform

texts:
This is what happens when my player character jumps and collides with a platform from the side. The player character tilts over or ends up upside-down or sometimes on its back.

How can I prevent this?


texts: Google Games Services Display Orientation

texts:
I'm developing a game using LibGDX and I'm using BaseGameUtils to implement Play Games Services in it. It's working very well. But my game is in landscape mode, so when I call leaderboard or achievements it opens up in landscape mode. I don't want that. I want the games services to open in portrait only. There's no entry of BaseGameUtils in my manifest file and I checked the Android Manifest file in BaseGameUtils module, but there's no <activity> in there.

How can I change the orientation when games services is displayed?


texts: I have been building and designing a hobby-tier game engine and I am currently working on supporting any amount of lights of any type. I checked out Unity and it supports multiple directional lights, what would that be useful for? Doesn't one directional light (without shadow map) already light the entire scene?


texts:
I want to be able to zoom in and out of the map using the scroll wheel. I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements.

so far, all I have is the resizing but I now need to change the map position.

What I have: map x and y; map width and height; cursor x and y.

Any help would be most welcome.


texts: A more data oriented design approach to Entity Component System game engine

texts:
I'm creating my first c++ game engine project (for learning purposes) and in it I've attempted to implement an entity/component system utilizing some data oriented design principles while also not fully giving up my object oriented way of thinking. I have data only component structs:

(Example)

Position.h

struct Position
{
    Vector3D position{ 0.0f, 0.0f, 0.0f };
};

which are stored in arrays within my SceneManager class:

SceneManager.h

class SceneManager
{
    //Some other code....

private:
    //So only systems have access to component arrays
    friend class BGraphics::RenderSystem;
    friend class BInput::InputSystem;
    friend class BPhysics::MovementSystem;
    friend class BPhysics::CollisionSystem;
    friend class BAudio::AudioSystem;

    //Component arrays. Each index of the arrays represents an entity.
    //So positionComponents.at(1) represents entity 1's position.
    Array<Position, 10> positionComponents;
    Array<Velocity, 10> velocityComponents;
};

As you can see, my engine's system classes are the only ones who have access to the component arrays and so every system can process components. There are some other things involved in this setup that I don't want to get too deep into for simplicity's sake. My issues are as follows:

Each system accepts a SceneManager reference in an Update function like so:

RenderSystem::Update(SceneManager& scene)
{
   //Use scene component arrays necessary for processing...
}

What I'm struggling with is right now my components seem like global variables in that every system has access to them and can change their state. Though it seems like a lot of data oriented design involves structs like these with public data for which other functions can operate on, changing their state. With that being said, is there something I'm missing with my implementation that would make my component data more encapsulated and safer? How am I suppose to think about handling data in a safe way when utilizing data oriented design? Any clarity is appreciated.


texts: I am making a Tetris clone with a new idea but I won't use the Tetris or Tetriminos name in the game I will refer to them as Tetrominos. Will there be copyright issues if I release this game? Does the Tetris company own the right to produce "Tetris" games?


texts: Can I use inheritance to inherit properties from the editor?

texts:
The title might not be very clear, so I'll give an example.

Let's say I have two types of buttons in my game's UI : buttons of the category A and buttons of the category B.

They are both very similar, and have the same "Normal Color", "Highlighted Color", etc. The only difference is that they have a different "Pressed Color". For example, A buttons are red when pressed and B buttons are blue.

Now I could create two different prefabs as models for A buttons and B buttons, and call it a day, but I might end up adding some more categories of buttons later (C, D, etc.). And each one has a different "Pressed Color". And if I decide to change the "Normal Color" for each button, I would have to change it in each prefab.

So is there a way to do some kind of... prefab inheritance I guess? For example, each category prefab would inherit from a more high level prefab that would define the "Normal Color", "Highlighted Color", etc.

If yes, how?


texts: Why are my Hello World Box2D project's collisions off by twice the size of my boxes?

texts:
I've been implementing Box2D into my engine but have run into a snag. I decided to rebuild the helloworld project inside of my own engine (it is almost identical), of which I will snip here in a moment. Firstly, the problem:

The dynamic body collides too early on the ground body. The ground body is much larger than is being rendered.

Code:

GameHandler.cpp

#include "GameHandler.h"

gameHandler::gameHandler()
{
    world_ = new b2World(gravity); //Gravity = 0, -10

    gfx = graphics(ResourceManager::getShader("main"));

    enter();
}

void gameHandler::update()
{
    float32 timestep = 1.0f / 60.0f;

    int32 velocityIts = 6;
    int32 positionIts = 2;

    world_->Step(timestep, velocityIts, positionIts);

    std::cout << "bodyx: " <<
    body_->GetPosition().x << " \t\tbodyy: " <<
    body_->GetPosition().y << " \tgroundx: " <<
    ground_->GetPosition().x << " \tgroundy: " <<
    ground_->GetPosition().y << "\n";

    input.update();

    if (input.isKeyDown(SDL_SCANCODE_RIGHT))
    {
        body_->ApplyForce(b2Vec2(20, 0), b2Vec2(0, 0), true);
    }
    if (input.isKeyDown(SDL_SCANCODE_LEFT))
    {
        body_->ApplyForce(b2Vec2(-20, 0), b2Vec2(0, 0), true);
    }

}

void gameHandler::render()
{
    gfx.drawSprite(Texture(), ground_->GetPosition(), groundSize, 0.0f, glm::vec3(1.0f, 1.0f, 0.0f));
    gfx.drawSprite(Texture(), body_->GetPosition(), bodySize, body_->GetAngle(), glm::vec3(0.0f, 1.0f, 0.0f));
}

void gameHandler::enter()
{

    groundSize = b2Vec2(10.0f, 10.0f);
    bodySize = b2Vec2(2.0f, 2.0f);

    // Define the ground body.
    b2BodyDef groundBodyDef;
    groundBodyDef.position.Set(0.0f, -20.0f);

    // Call the body factory which allocates memory for the ground body
    // from a pool and creates the ground box shape (also from a pool).
    // The body is also added to the world.
    ground_ = world_->CreateBody(&groundBodyDef);

    // Define the ground box shape.
    b2PolygonShape groundBox;

    // The extents are the half-widths of the box.
    groundBox.SetAsBox(groundSize.x, groundSize.y);

    // Add the ground fixture to the ground body.
    ground_->CreateFixture(&groundBox, 0.0f);

    // Define the dynamic body. We set its position and call the body factory.
    b2BodyDef bodyDef;
    bodyDef.type = b2_dynamicBody;
    bodyDef.position.Set(0.0f, 4.0f);
    body_ = world_->CreateBody(&bodyDef);

    // Define another box shape for our dynamic body.
    b2PolygonShape dynamicBox;
    dynamicBox.SetAsBox(bodySize.x, bodySize.y);

    // Define the dynamic body fixture.
    b2FixtureDef fixtureDef;
    fixtureDef.shape = &dynamicBox;

    // Set the box density to be non-zero, so it will be dynamic.
    fixtureDef.density = 1.0f;

    // Override the default friction.
    fixtureDef.friction = 0.0f;

    // Add the shape to the body.
    body_->CreateFixture(&fixtureDef);
}

Projection:

float lowerX = -25.0f, upperX = 25.0f, lowerY = -15.0f, upperY = 25.0f;
glm::mat4 projection = glm::ortho(lowerX, upperX, lowerY, upperY, -1.0f, 1.0f);

Gif:

The box falls off after reaching the end of what seems to be the ground box scaled to about double it's size to the left. The same thing happens going to the right but the invisible ledge is much shorter.

The same thing does happen inside of the helloworld.cpp project provided in the examples:

Strangest thing, any help?

Thanks in advance for any help!


texts: OpenGL textures loaded with SDL_Image display with no alpha

texts:
I am making a game using OpenGL, with SDL_Image employed to load the textures. When drawn on screen, there's no alpha -- in an exact square around the opaque contents of the texture, black is drawn; outside that space, white is drawn. Here is my OpenGL init code...

SDL_SetVideoMode(windowWidth, windowHeight, 16, SDL_HWSURFACE|SDL_GL_DOUBLEBUFFER|SDL_OPENGL);
glClearColor(0, 0, 0, 0);
glClearDepth(1.0f);
glViewport(0, 0, windowWidth, windowHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, windowWidth, windowHeight, 0, 1, -1);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glLoadIdentity();

...here is my image loading function...

SDL_Surface *loadImage (const char *filename, bool alpha = true) {
    SDL_Surface* loadedImage = NULL;
    SDL_Surface* zoomedImage = NULL;
    SDL_Surface* optimizedImage = NULL;

    loadedImage = IMG_Load(filename);

    if (loadedImage != NULL) {
        zoomedImage = zoomSurface(loadedImage,windowScaleH/4,windowScaleH/4,SMOOTHING_ON);
        SDL_FreeSurface(loadedImage);

        if (alpha) optimizedImage = SDL_DisplayFormatAlpha(zoomedImage);
        else optimizedImage = SDL_DisplayFormat(zoomedImage);
        SDL_FreeSurface(zoomedImage);
    }

    return optimizedImage;
}

...here is the code I actually use to create the GL texture...

GLuint thisIsMyTexture;
glGenTextures(1, &thisIsMyTexture);
temporarySurface = loadImage("theimagetomytexture.png");
glBindTexture(GL_TEXTURE_2D,thisIsMyTexture);
glTexImage2D(GL_TEXTURE_2D, 0, 4, temporarySurface->w, temporarySurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, temporarySurface->pixels);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

...and the drawing code itself.

glBindTexture(GL_TEXTURE_2D,thisIsMyTexture);
glBegin( GL_QUADS );
    glTexCoord2f(0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f);
    glTexCoord2f(1.0f, 0.0f); glVertex3f(32.0f, 0.0f, 1.0f);
    glTexCoord2f(1.0f, 1.0f); glVertex3f(32.0f, 32.0f, 1.0f);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(0.0f, 32.0f, 1.0f);
glEnd();

That's all the relevant information I can think of. Help would be appreciated! :D


texts: OpenGL - How come drawing sprites takes so much performance

texts:
I'm wondering how drawing simple geometry with textures can eat up so much performance (below 60fps)? Even my good graphics card (GTX 960) can "only" draw up to 1000 sprites smoothly. The textures I'm using are all power of 2 textures and don't exceed a size of 512x512. I'm even filtering with GL_NEAREST only.
The sprites themself are random generated in size. So there are no 1000 fullscreen quads, which would be no real use case.

I'm drawing my sprites batched, meaning I have one dynamic vertex buffer and a static index buffer. I update the vertex buffer every frame with glBufferSubData once and then draw everything with ``glDrawElements`. I have about 5 different textures which I bind once per frame resulting in 5 draw calls. For rendering I'm using only one shader which is bound once the application starts.
So I have 5 texture bindings, 5 draw calls, and one vertex buffer update per frame which is not really that much.

Here is an example with one texture:

val shaderProgram = ShaderProgram("assets/default.vert", "assets/default.frag")
val texture = Texture("assets/logo.png")
val sprite = BufferSprite(texture)
val batch = BufferSpriteBatch()

val projView = Matrix4f().identity().ortho2D(0f, 640f, 0f, 480f)

fun setup() {
    glEnable(GL_TEXTURE)
    //glColorMask(true, true, true, true)
    //glDepthMask(false)

    glUseProgram(shaderProgram.program)
    texture.bind()

    batch.begin()
        for(i in 1..1000)
            batch.draw(sprite)
    batch.update()
}

fun render() {
    glClear(GL_COLOR_BUFFER_BIT)

    stackPush().use { stack ->
        val mat = stack.mallocFloat(16)
        projView.get(mat)
        val loc = glGetUniformLocation(shaderProgram.program, "u_projView")
        glUniformMatrix4fv(loc, false, mat)

        batch.flush()
    }

}

The batch.draw() method puts the sprites vertex data in a cpu side buffer and batch.update() uploads everything to the gpu with glBufferSubData.
And setting up the spritebatch looks as follows:

glBindBuffer(GL_ARRAY_BUFFER, tmpVbo)
            glBufferData(GL_ARRAY_BUFFER, vertexData, GL_STATIC_DRAW)
            glEnableVertexAttribArray(0)
            glEnableVertexAttribArray(1)
            glEnableVertexAttribArray(2)
            glVertexAttribPointer(0, 2, GL_FLOAT, false, 24 * sizeof(Float), 0)
            glVertexAttribPointer(1, 4, GL_FLOAT, false, 24 * sizeof(Float), 2.toLong() * sizeof(Float))
            glVertexAttribPointer(2, 2, GL_FLOAT, false, 24 * sizeof(Float), 6.toLong() * sizeof(Float))

            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, tmpEbo)
            glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW)

I was profiling my program first, but updating the vertex buffers and all the geometry takes about 10% of the total time per frame. But swapping the buffers takes up the rest of the 90% frame time.

So I'm asking, how can such big AAA games render their scenes with millions of vertices, if drawing pixels is such a time consuming task? I know that their is a lot of optimizations in the code, but still.


texts:
I have found several entity system frameworks for other languages besides C++, like Ash and Rush for ActionScript and Artemis for Java and C#.

My question is whether there exists a framework like one of the ones mentioned above for C++?


texts: How to optimize a box2d simulation in action game?

texts:
I'm working on an action game and i use box2d for physics. The game use a tiled map.

I have different types of body:

Static ones used for tiles
Dynamic ones for player and enemies

Actually i tested my game with ~150 bodies and i have a 60fps constantly on my computer but not on my mobile (android). The FPS drop as the number of body increase.

After having profiled the android application, i saw that the World.step took around 8ms in CPU time to execute.

Here are few things to note:

Not all the world is visible on screen, i use a scrolling system
Enemies are constantly moving toward the player so there is alaways to force applied to their body
Enemies need to collide between each others
Enemies collide with tiles

I also now that i can active/desactive or sleep/awake bodies.

Considering the fact that only a part of the enemies are possibly displayed on screen, is there any optimizations i can do to reduce the execution time of box2d simulation?

I found a guy trying an optimization based on distance of enemies from the player (link). But i seems like he just desactives far bodies (in my case, i could desactive bodies that are not visible). But my enemies need to move even when they are not visible on screen, and applying forces will not workd on inactive bodies. Should i play with sleeping bodies here?

Also, enemies are composed by two fixtures and are constantly colliding with each others and with tiles but i really never need to get notified about that. Is there anything i can do to optimize this kind of scenario?

Finally, am i wrong to try to run simulation at 60FPS on mobile and should i try to make it run at 30FPS?


texts: What languages are used to develop MMORPGs like EVE Online and WOW?

texts:
As I understand it, MMORPGs are games that run on your computer like any other normal 3d video game but, with each action that happens with in the game, changes are made to the universe via HTTP calls to the server. So the players computer does all the heavy lifting in terms of rendering the graphics and animations but, web frameworks do the online communication.

So I am wondering what web frameworks, web servers and databases are being used to create MMORPGs like EVE Online and W.O.W.?
Also, what programming languages and 3d game engines are being used to make the client side (3d graphics/animation/sounds) part of the game?


texts: Whats the most efficient method for controlling entities?

texts:
I'm creating a tower defense game and I'm having logistical issues trying to figure out how to best have all of the enitites do their apporiate task.

I have considered just constantly looping through a list of all the game entities calling a onAction() method, but I'm not sure if that is effective.

I have also considered having each entity be a thread, but when I am dealing with hundreds of entities, some of which don't need thread time, I'm back to square one.

Can I get any suggestions on a solid approach? Am I on the correct track with my first idea?

Thanks for any help ~Aedon


texts: How to get a Vector2 location of an object? (Unity2D javascript)

texts: I need to make an "AI" that makes a ball try to touch the player. But Vector2.MoveTowards()needs a Vector2 variable but how do i get the location of an object?


texts:
When you click on a hand should trigger the script. I do not understand how this script to the button.

Here's a script, even though he can not correct:

using UnityEngine;
using System.Collections;

public class hand : MonoBehaviour {
    public Transform player;
    public Transform mushrums;

    private Animator anim;
    private bool pick_up;

    void Start () {
        anim = GetComponent<Animator> ();
        pick_up = false;
    }

    void Update () {
        anim.SetBool ("pick_up", pick_up);

        float dist = Vector3.Distance(player.position, mushrums.position);
        Debug.Log(dist);

        if (dist <= 58.5f)
        {
            pick_up = true;
            //here the removal of the object to which came
        }
        else
        {
            pick_up= false;
        }
    }
}

The button should be activated only at a certain distance from the object to which came.


texts: Climate / weather generation on 3d hex map

texts:
I am working on 3d hex map game. I am aiming to dynamical generate map (as new players joins). To make the map realistic I am looking for some climate/weather models which possibly I could use so that the generated terrain / game environment remains realistic.

Currently I am not having any system implemented to generate hex map. I was thinking of using height map but I am looking for ways to connect with it also such variables as aridity, temperature so that it is as realistic as possible. I may not exclude that in future I will want players to be able to modify the climate (e.g. via spells) and thus, the map generation mechanism should work not only during map generation but also should be able to calculate further changes in environment caused by players. It would be the best if given model would be able to be used also to calculate impact of climate and weather on crops, speed of troops and so on.

Would you be so kind and advise on any ready climate generation/administration solutions? I am looking for something quite complex to be from one hand maximally realistic and from the other  in further able to generate game variables such as current weather information.


texts:
I have tried to follow nehe's opengl tutorial lesson 2. I use sfml for my window creation. The problem I have is that both the triangle and the quad don't show up on the screen:

#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <iostream>

void processEvents(sf::Window *app);
void processInput(sf::Window *app, const sf::Input &input);

void renderCube(sf::Window *app, sf::Clock *clock);
void renderGlScene(sf::Window *app);

void init();

int main()  {
    sf::Window app(sf::VideoMode(800, 600, 32), "Nehe Lesson 2");

    app.UseVerticalSync(false);

    init();

    while (app.IsOpened())  {
        processEvents(&app);

        renderGlScene(&app);

        app.Display();
    }

    return EXIT_SUCCESS;
}

void init()  {
    glClearDepth(1.f);
    glClearColor(0.f, 0.f, 0.f, 0.f);

    // Enable z-buffer and read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    // Setup a perpective projection
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluPerspective(45.f, 1.f, 1.f, 500.f);

    glShadeModel(GL_SMOOTH);
}

void processEvents(sf::Window *app)  {
    sf::Event event;

    while (app->GetEvent(event))  {
        if (event.Type == sf::Event::Closed)  {
            app->Close();
        }

        if (event.Type == sf::Event::KeyPressed &&
            event.Key.Code == sf::Key::Escape)  {
            app->Close();
        }
    }
}

void renderGlScene(sf::Window *app)  {
    app->SetActive();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clear the screen and the depth buffer
    glLoadIdentity();                   // Reset the view

    glTranslatef(-1.5f, 0.0f, -6.0f);   // Move Left 1.5 units and into the screen 6.0

    glBegin(GL_TRIANGLES);
        glVertex3f( 0.0f, 1.0f, 0.0f);  // Top
        glVertex3f(-1.0,-1.0f, 0.0f);  // Bottom Left
        glVertex3f( 1.0f,-1.0f, 0.0f);  // Bottom Right
    glEnd();

    glTranslatef(3.0f, 0.0f, 0.0f);

    glBegin(GL_QUADS);  // Draw a quad
        glVertex3f(-1.0f, 1.0f, 0.0f);
        glVertex3f( 1.0f, 1.0f, 0.0f);
        glVertex3f( 1.0f,-1.0f, 0.0f);
        glVertex3f(-1.0f,-1.0f, 0.0f);
    glEnd();
}

I would greatly appreciate it if someone could help me resolve my issue.


texts: Retrieving JSON return value from function and parsing in Construct 2

texts:
I would like to know how to parse a JSON object and parse each value into either an array, or something that I can use to set values of several global variables in my project file. I want to avoid editing the Javascript file itself, so please try to provide an approach that can be done in Construct itself rather than an external way.

Code sample

 axonify.game = {
  gameData: function() {
    data = {
      name: 'Block Mania',
      timeLimit: 30,
      addedTimePerQuestion: 0,
      addedTimePerCorrectQuestion: 15,
      questionCount: questionCount
    };
    return data;
  },


texts: Authentication and keeping track of users for a cross platform game (Steam+mobile)

texts:
I've got a question about authentication/user accounts. I'm building a game using Unity that'll be sold on Desktop (through Steam) and Mobile (Play/App Store).
The game has online multiplayer functionality. I'd like to be able to verify if the clients that connect to the server have actually bought the game and have the option to store data for these profiles (nickname, scores, etc.). Obviously I'll need some sort of account system/database for that, but I'd like to know what the most common approach to this problem is for games that are sold on different platforms.
What I'd like to avoid is having to create my own account system, since then I'd have to deal with password reset functionality, e-mails, GDPR, that kind of thing. Also I'd like for the user to have a seamless experience after buying the game and not having to register yet another account specifically for my game.


texts: How to factorize code in Unreal Kismet (i.e. "Material Function"s for Kismet)

texts:
In the Unreal Development Kit, when using the Material Editor, one can factorize frequently-used groups of nodes by creating a Material Function (content Browser → right-click → new matrial function, IIRC).

When defining the behaviour of some actor in Kismet, one can easily have a dozen nodes involved.

If I have many actors that share the same behaviour, then I'll copy-paste these nodes, and change the variables so they point to the other actors.

This leads to inconsistencies (a modification in the behaviour of an actor isn't propagated in the copy-pasted nodes), complexity (you end up with hundreds of nodes), and generally useless effort.

My question is : Can I create a "kismet function", just like a material function ?

Note: I'd rather avoid using UnrealScript.

I don't even know where to type UnrealScripts, don't know where the documentation is and more generally don't have enough time to invest in learning UnrealScript.
This "kismet function" feature must be usable by graphists (with little programming knowledge).
If a (simple) script suffices to add this feature in the Kismet editor, so that one can create several "functions" without using UnrealScript, then fine, but I don't really want to have to write a script each time I want to factorize a few nodes.

Thanks for any information !


texts: get position of GameObject on rendertexture from camera

texts:
I'm rendering the camera output to an rendertexture on a plane.  This works fine. But I want to put GameObjects on the rendertexture on positions of world objects that are visible on the camera.

camera.WorldToViewportPoint(obj.transform.position)

shows the correct positions, but is not mapped to the rendertexture. How can I do this?

So it's GameObject in world > camera input >  plane with RenderTexture > world or local position of gameobject on top of rendertexture plane.


texts: Declaring another alpha or beta testing after a game app for Android (APK file) is uploaded and already published in Google Play Store

texts: This question is related about alpha or beta release in Google Play Store. . Let's say my app (APK file) was uploaded in alpha/beta testing. If one of the testers satisfied or quick fixes on the bugs, then I'm gonna go promote to production, which means publishing an app. Now, let's say I wanna go for another alpha or beta testing for the next version before updating new version in production. I have to test it; let's say testing for the leaderboard or achievements created from the Game Services at Google Play Developers Console, adding Google Play Games plugins for Unity to the app, and then uploading the new APK version for the next beta release before updating new version in production. Is it possible or not?


texts: Unity 5 Client RPC call: Failed to Invoke ClientRpc

texts:
I have a Unity 5 client and server running. On the server a path is generated and I want the client to receive the position of each target node on this path. Following the Client RPC calls section here http://docs.unity3d.com/Manual/UNetActions.html I have created the following script:
public class AccessingTargetPos : NetworkBehaviour {

[ClientRpc]
void RpcPosFromServerToGoTo(Vector3 pos)
{
    UnityEngine.Debug.Log ("Going to ... " + pos);
}

public void PrintPath(Vector3 pos)
{
    if (isServer)
    {
        UnityEngine.Debug.Log (pos);
        UnityEngine.Debug.Log("Send Pos ...");
        RpcPosFromServerToGoTo (pos);
        UnityEngine.Debug.Log("Sent!!");

    }
}

}

Both the client and the server have this script, assigned to a game object. However with the above I receive the following in my console:

At the moment all I want is for the client to output the positions received. When I get this I'll move on. I have followed the link, where have I went wrong here?


texts:
My game has 3D environment which is partitioned in 2d cells(nodes). I have implemented A* for path finding.

Now I am just breaking my head to how to implement the algorithm to move the hero to the nearest attackable range node/point when the enemy is out of attack able range.

Which means, it should satisfy two conditions

Target whithin attackable range
No obstacles in between the target
and attacker

See below picture (pardon for my bad drawings)

Brown boxes are obstacles
Attacker/hero is in the cell highlighted with Turquoise color dot, the circle is  the radius/size of the model.
Target is the red dotted color cell, surrounded with red color circle to indicate the size of the model
Green circle is the radius where hero has to move to some where inside that location to attack (its the radius of hero's attack range)
Blue dots are the A* path to reach from hero position to target position

When the player issues attack command, hero should move to the nearest attack able node and start attacking.

Finally I thought of below algorithm

Calculate radius to scan - This is the sum of attacker radius + attacker weapon radius + target radius
Get nodes fall within the radius (from step 1) from targets position
Find path from attacker to target using A*
Keep walking in the path (from step 3)
check if current node is in the scanned nodes (from step 1)
If true,
Check that no obstacle are in between
If true, attack, if false keep walking (repeat step 4)

If we put together the algorithm and the figure1

The A* gets the path of 9 node to reach the target
After moving 5 steps, it enters the attackable range, since there is obstacle between the target, it take two more steps where it finds no obstacles and stats attacking.

I am not sure if this is the optimized method to achieve this but I am not getting alternative solution.

Very particular to the steps 2-5 which looks little weird and process intensive to me.

I am using actionscript 3 and Flare3D (Stage3D API)


texts: How to model interentity membership in entity-component architecture?

texts:
I'm falling in love with simple grace of entity-component design, although I still have issues breaking from MVC and OOP practices. Some of my game entities have membership relationships with each other (ex: a player is a member of a city, a city is a member of a nation), and I am unsure on the best way to implement it.

My initial reaction is to have a a MemberOfCity component that points to the appropriate city component, but components are suppose to have no references to each other. My other option is to have a System do it, but that would require the system to persist data outside of a component.

Is there a clean way to do this in an entity-component design, or am I trying to use a hammer on a screw and should use a hybrid/another approach?


texts: Getting a control name/Displaying tooltip text

texts:
I am developing a character creator using Windows Forms (because apparently I can't create menus in Unity), and I want to display some tips and descriptions in a RichTextBox located by the options when the user's mouse hover by its GroupBoxes.

Since I am fairly new to programming I don't know if getting all the controls' names one by one is the optimal, so I want to grab the controls' names inside of the tabControl control that I am using to organize everything.

private void TabControl1_MouseHover(object sender, EventArgs e)
        {
            foreach(Control c in this.Controls)
            {
                string name = c.Name;
                TooltipText(name);
            }
        }

And I also have a method where I will write the text that will be displayed in the RichTextBox

private string TooltipText(string name)
        {
            if(name == "Name:")
            {
                return "blabla";
            }
            else
            {
                return "none";
            }
        }

I've tried a generic method to show a message box if the control was detected and, as I suspected, nothing showed up:

private void TooltipText(string name)
        {
            if(name == "LBL_Name")
            {
                MessageBox.Show("hey");
                return;
            }
        }

How can I properly detect the GroupBoxes or other types of controls inside of the TabControl control and also display the text in the box beside it?


texts: How can I make a collection of mini-games in XNA where the user can download packs of minigames and the main .exe can run them without being altered?

texts:
I'm currently making a PC game in XNA. It's actually a collection of mini-games (there's 3 mini-games at the moment) however I plan to make and add more, in downloadable 'packs'.

My question is, what's the best way to achieve this?

Currently my thoughts are:

Create a 'game' interface
Build games to this interface but create them as .dlls
Have the main .exe file scan a directory and load in the .dlls at runtime.

I've not messed around with the idea much, but I know there are applications at-least that use this plug-in approach (Notepad++ seems to), but I'm not sure of any games that do (although I'm sure they must exist). However it seems that this is a problem that has been solved previously, so I'm wondering if there's any form of established best-practice.


texts: How can I support more than one resolution/language on WP7/8?

texts:
I want that my Windows Phone game runs on the following three resolutions: 480x800, 768x1280 and 720x1280. And maybe later on 1920x1080.
But in the XAP file information, it's just written "Resolution(s) WVGA". What can I support more resolutions than just WVGA?
In addition, I want to support more than one language. At the moment, I can just choose English in the Dev Center menu, but I want to support French, Spanish and German too. How can I support French, Spanish and German? I don't know how to add these languages.
I uploaded my XAP file in the Dev Center and it gives me the following informations:

Select a XAP above to view or edit its Store listing and other info.
XAP version number  1.0.0.0
XAP details detected from file
File name WindowsPhoneGame2.xap
File size 167 KB
Supported OS 7.1, 8.0
Resolution(s) WVGA
Language(s) EnglishNorthAmerica
Capabilities ID_CAP_NETWORKING
XAP's Store listing info
A XAP file can contain multiple languages. Select a language to add Store listing info specific for that language.
English
Description for the Store:


texts: What do I have to take into consideration when developing both singleplayer and multiplayer coop without dedicated servers?

texts:
The premise is simple - a game that can be played in singleplayer mode and that allows seamless partying for coop without dedicated servers. This would of course require server and client components and a singleplayer session would be nothing other than a client joining a (local) server (running in the background). Such a local server would in turn allow others to connect seamless and join a friends session without the need of restarting in a multiplayer game session. And eventually it would make development slightly "easier" since I would not need to work on two different game modes (that behave the same in this setting). I was curious about the workflow during development and some questions came to my mind I'd like to get some input on:

At first I'd be tempted to develop everything in the game client itself and not bother about the server since testing the gameplay and game elements themselves would be straightaway easier. With this mindset though I might have trouble moving the game logic that worked locally in the game to the server component and might end up tweaking something. I'd like to know whether it is feasible/reasonable to develop the core elements of the singleplayer and afterwards migrating to a server/client structure or should I plan on working on both ends simultaneously?
With regards to networking I don't have any experience with it in C++ and appropriate libraries (although I am fairly fluent in C++ and my game will be written using it) and was considering to take a bold approach by ignoring performance at first and sticking to something I am familiar with. Basically I'd write the server using C# or Node and the client networking code in C# (and possibly some library for shared components between the two) and would need a C++/CLI wrapper to call the client network code in my game itself. I'd have extra work to implement the bridge but ultimately I'd be able to get the basics going no matter how patchwerk they might be. At some point of course I'll probably have to translate all three of them (server, client, shared codebase) to native C++ not only for performance but for compatibility. So do you have suggestions on whether I should be going for something "patchy" using familiar tools and libraries and then migrating it later or should I invest the time to start "properly" with the same codebase and language on both sides?
Finally I have a question that boils down to the design of partying / matchmaking. Usually in multiplayer games you join via directly entering an IP address or using features like the Steam friend list. I'd really like to include a way to connect to specific games without having to mess around with ip addresses and using something like a lobby or even better a friend list. In this case though I'd need a small dedicated server for managing users and such friend lists. Is there any other design or way to connect besides using raw IP addresses?


texts:
I'm trying to implement a simple "lighting" system that alters a value of light between 0.0-1.0, 1.0 is midday 0.0 is total blackness.

Are there any "good" information regarding this particular subject or is it something that you have to develop yourself and adjust to your game in particular. What I'm probably looking for is an algorithm that is flexible and could work by changing values like midday point and such.

My algorithm uses 12:00 / 12PM as it's center point and at that time it's 1.0 in lighting. What I'm trying to do is perhaps "change" the midday point to any value to say 10 and it should still work the same, and perhaps also be able to alter the number of  hours the midday can be. Perhaps so that the lighting rises and falls exponentially. So that between night and 4 it raises slowly, between 4 and 8 it raises much faster and at 10 it's reached it high point until 14 when it starts to fall again but in the reverse order.

My simple algorithm only calculates a value between 0.0 and 1.0 and if there is any good info or some suggestions on how to "improve" this method or any other information regarding this subject it would be greatly appreciated.

My algoritm goes as following:

If (CurrentHour < (HoursPerDay / 2))

    Lighting = CurrentHour / (HoursPerDay / 2)
    Lighting += (CurrentMinute / MinutesPerHour) * (1 / (HoursPerDay / 2))

Else

   Lighting = 1 - ((CurrentHour / (HoursPerDay / 2)) - 1)
   Lighting -= (CurrentMinute / MinutesPerHour) * (1 / (HoursPerDay/2))

MIN_VALUE = 0.3f;
Max(MIN_VALUE, Min(Lighting, 1f))

or in C# code:

public float CalculateLighting(uint hour, uint minute, uint minutesPerHour, uint hoursPerDay)
{
    float lighting = 1f;

    if (hour < (hoursPerDay / 2))
    {
        lighting = (hour / (hoursPerDay / 2)) * lightingMax;
        lighting += ((minute / minutesPerHour) * (1f / (hoursPerDay / 2))) * lightingMax;
    }
    else
    {
        lighting = lightingMax - (((hour / (hoursPerDay / 2)) * lightingMax) - lightingMax);
        lighting -= ((minute / minutesPerHour) * (1f / (hoursPerDay / 2))) * lightingMax;
    }

    lighting = MathHelper.Clamp(lighting, lightingMin, lightingMax);
}

This way when the time is 6:00 AM the value is (6/12) and the same for (12+6) and also I clamp the results so I get a value between 0.3 and 1.0 or change that to whatever in case you wanted it to be Winter season so it's darker you can raise that value. This is however a very simple implementation of this concept.

Some functions that I'd like to bring in to it is:¨

When is the "midday" and how long is it? Say it's 4 hours between 10-14. During this time it should always be 1.0 in lighting.
Change the midday point to anytime or remove it completely. During dark nights in a game perhaps the sun shouldn't rise fully.
"Somehow" perhaps make it increase slow and decrease fast by using some value for each. If the sun rises slowly but falls rather quickly afterwards. Exponentially raise and exponentially fall faster.

Just some ideas I'm looking for. It doesn't have to be realistic, just a sense that the weather can change. This value should be a value between 0.0 and 1.0 or adjustable (for extra bright days or something) due to the fact that it can be used to light the entire scene. A reference point to how bright it is in the game world.

How can I best extend my algoritm and improve it and perhaps implement new features?

Any suggestions are appreciated or some information on good implementation of a Day-Cycle system.


texts: How important is it to learn openGL when using game enginges such as Unity, cocos2d-x, lib-GDX and generally in game developing? Can you still create very complex, high-quality games without knowing openGL?


texts: Where to start, to develop an online Backgammon game?

texts: I would like to develop a backgammon game to play against other players online, as a way of learning more Javascript/jQuery and a little game development. I'm a web developer and most of my experience is in PHP. I have minimal Javascript experience and no game development experience. Where should I start? Are there any particular books, tutorials, libraries, or frameworks that would help give me a jumpstart? As a beginner, am I better of using the DOM or Canvas?


texts:
SoundEffect has SpeedOfSound property. I'm trying to use it, but it doesn't work:

SoundEffect.SpeedOfSound = 600.0f;
SoundEffectInstance soundEffectInstance = stepsSound.CreateInstance();
soundEffectInstance.Volume *= 0.5f;
soundEffectInstance.Play();

How to use it? How to set speed of sound?


texts: Proper way to draw 1000 billboards that always face the camera

texts:
I have up to 1000 visible GameObjects with trivial plane meshes, which are essentially sprites/billboards and which should always face in the relative direction -camera.forward.

There are so many ways to do this that I have trouble sorting the good ways from the bad ones.

The straightforward way is to use a geometry shader, but that isn't supported on most devices, so that's out.
Using a script is nice, easy, simple, and wasting performance.
Using a vertex shader and passing in center coordinate of the billboard through properties feels clean but is wasting even more performance because it breaks batching.
Doing it in a vertex shader and passing in center coordinate of the billboard through through uv2 feels brittle and wrong, but will be the most performant.

Ideally, someone has a better solution. If not, maybe someone can make a convincing argument for one of the approaches?

Related: Rotate object to always face camera, Efficient billboarding sprites in Unity 5


texts:
I am using unity 4.5.1f3 and using the Vuforia sdk 5.0.5.I have downloaded the sample project from the Vuforia site.When I tried to run the sample of Imagetarget project,it asked to add license key.Then I added licensed key to the app.Then when I runned the project again its showing me and error

MissingMethodException: Method not found:   'UnityEngine.Behaviour.get_isActiveAndEnabled'.
Vuforia.VuforiaAbstractBehaviour.UpdateStatePrivate (Boolean forceUpdate, Boolean reapplyOldState)
Vuforia.VuforiaAbstractBehaviour.Update ()

The Image marker detection can run but the camera video doesn't show in the background.
can anybody help me solving the issue?


texts:
I'm having troubles saving how much of an item I have in my game. Right now I have it so the price goes up the more items you buy, that works, but every time I reset the game, the count goes back to 0, while the price acts as if the count is at a higher number.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ItemManager : MonoBehaviour {

public UnityEngine.UI.Text itemInfo;
public GPS gps;
public Click click;
public float cost;
public int tickValue;
public int count = 0;
public string itemName;
private float baseCost;
private Slider _slider;

void Start()
{

    Load ();
    baseCost = cost;
    _slider = GetComponentInChildren<Slider> ();
}

void Update()
{
    PlayerPrefs.SetFloat ("Count", count);
    PlayerPrefs.SetFloat ("Cost", cost);

    itemInfo.text = itemName + " (" + count + ") " + "\nCost: " + cost + "\nGold: " + tickValue + "/s";

    _slider.value = click.gold / cost * 100;

    if (_slider.value >= 100) {
        GetComponent<Image> ().color = buyColor;
    }else{
        GetComponent<Image>().color = standard;
    }
}

public void BuyItem()
{
    if (click.gold >= cost)
    {
        click.gold -= cost;
        count += 1;
        cost = Mathf.Round (baseCost + Mathf.Pow (2f, count));
    }
}

public void Load()
{
    count = PlayerPrefs.GetInt ("Count");
    cost = PlayerPrefs.GetFloat ("Cost");
}
}

I've tried to figure this our for hours, and I just don't know what to do with this.


texts:
Is it possible to have a diagonal movement animation in monogame/xna?

As far as I can tell it's not possible to recognise multiple keypresses (ie "A && W" or "S && D") as unique events - everything I've seen regarding diagonal movement basically goes;

if(W)
{
    player.position.x = player.position.x + 1
}
if(S)
{
    player.position.x = player.position.x - 1
}
if(A)
{
    player.position.y = player.position.y - 1
}
if(D)
{
    player.position.y = player.position.y + 1
}

And that obviously works in most instances, my problem is I have specific diagonal movement animations that I need to display, my characters are people and I can't just rotate them like a ship or a car - and as far as I can tell....

if(W && A)
{
    player.position.x = player.position.x + 1
    player.position.y = player.position.y - 1
}

Isn't possible?

The only way I can think to accomplish what I need is to detect diagonal movement after the input handling - ie if both x AND y positions are different or are going to be different to the previous position, set the relevant diagonal to true and show the relevant animation.

Is there a 'correct' or easier way to do this?


texts: Implementing priority structure into a behavior tree, to react to player actions

texts:
My goal is to have a behavior tree that can run alone (autonomously) but also react to input from the player.
I'm making an AI for a hack and slash game where the AI will fight you, chase you, etc. and play defensive based on certain stats (health etc), but I want to add an additional layer; events from player. Say the player attacks, I want a random chance maybe 5-10% to trigger a dodge or step-back from the AI.
Currently I have its own selector running, but that is not sufficient, as it just has same priority or triggers on the same level as the other selectors / sequences in the tree. So how do I go about implementing a priority into the tree?
I want to have dodge, which should be labelled as maybe priority 1 if the event triggers, else it should just go about its usual business.


texts: Show only some parts of a point cloud. OpenGl4

texts:
I am developing an opengl 4.0 app which is showing a point cloud. In the other hand, I have an array "pos" where I have some x,y,z positions:

pos[number of pos][3] , where 3 refers to [0]:x [1]:y [2]:z

I would like to show only the points of the point cloud which are inside of a sphere of radius R for any of the positions I have in the array pos. I was thinking in sending the array pos to the vertex shader that draws my cloud point and there, do a loop for each position and check if the distance between any of the positions and the vertex is less than a radius R. If so, I put an alpha colour of 1.0. If not, an alpha colour of 0. Something like:

Vertex:

#version 460

uniform mat4 viewMatrix, projMatrix;
uniform float Radius;

in vec4 position;
in vec3 pos[N];

in vec3 color;

float d;

out float Color;
out float AlphaC;

void main()
{
    Color = color;
    AlphaC = 0.0;

    for ( int i = 0; i < pos[i].length; i++ ) {
        d = distance(vec4(pos[i],1),position);
        if (d<Radius) {
            AlphaC = 1.0;
            break;
        }
    }

    gl_Position = projMatrix * viewMatrix * position ;
}

Fragment:

#version 460

in float Color;
in float AlphaC;

out vec4 outColor;

void main()
{
    outColor = vec4(Color, AlphaC);
}

But I am not sure how to send this pos array since this matrix is an Nx3 with N depending in the file of positions that I am using. Any idea? Does N has to be defined before compiling?


texts:
I'd like to do a simple 2D shadow calculation algorithm by rendering my environment into a texture, and then use raytracing to determine what pixels of the texture are not visible to the point light (simply handed to the shader as a vec2 position) .

A simple brute force algorithm per pixel would looks like this:

line_segment = line segment between current pixel of texture and light source

For each pixel in the texture:
{
  if pixel is not just empty space && pixel is on line_segment
       output = black
  else
       output = normal color of the pixel

}

This is, of course, probably not the fastest way to do it. Question is: What are faster ways to do it or what are some optimizations that can be applied to this technique?


texts: How do I set the Foot IK property of an animator state by code?

texts:
I would like to set Foot IK to enabled via code, but I can't find how.
Which type is "Foot IK" a part of?


texts:
So I'm planning to get into iPhone dev (2D games). I understand that my only real option is to get a Mac. I'll probably go the MonoTouch route.

I'm not sure what hardware to buy; I just want the minimum that'll be "good enough" to develop with. Some posts recommend a Mac Mini, although it seems on the more expensive side; even on the iPhone front, I'm not sure what to look for.

Also, I may skip on the iPhone until I'm ready to launch my first game, since I can get away with the MonoTouch evaluation version. (Albeit that it's probably not the best idea.)


texts: I'm already pretty adept at AS3 and all, and I have plenty of ideas for Flash games that I want to start making. However, I was wondering, when I've made my first one, how should I publish it, and how can I make it popular? I will upload it on my own website, but should I upload it to a more well-known site? And if so, which do you recommended? (Armor Games, Kongregate, etc.)


texts: Should my terrain be one big mesh or several medium ones?

texts:
While creating a subterranean level with probuilder (irregularly shaped rooms and corridors), I was wondering if I should merge all "terrain" meshes into one or keep them as separate meshes? What are the good practices ?

I'm creating each room as I go and its not hard to create openings and align doors vertices (with progrids) but once I start moving them around (like with polybrush) I'm sure it will soon be a nightmare. I can see pros and cons for both. Separate meshes would be easier to edit, duplicate or replace, probably better performances but at the risk of overlaps or holes because it would get hard to keep connected cleanly. I guess with one mesh you take the risk of having it eat memory and computation time, or having it too big to edit easily.

I settled on each mesh consisting of a room and all half-corridors going out of it, to hide the stitching and keep it simple. Still I wonder if there's a consensus.


texts: Using blend trees for a simple 2d character

texts: Let me start by saying that I'm not a animator and basically have no idea what I'm talking about. The character in the game has 3 states : indle(looks at camera) walk left and walk right. I've set up the transitions for all states but now I want to know how to blend from the idle state to each one of the walking states. This is how my animator looks like :


texts: How do I get the height of an XNA SpriteFont?

texts:
I have some text in a spritefont and I need to know the height in pixels.

I would have thought that MeasureString() would get me close to it, but it seems to just be about length.


texts: Is it normal for a game to use 100% CPU?

texts:
I just implemented multi-threaded input handling in my game engine where the code that polls the OS to gather input from it and time stamps them is in a separate thread and each frame in the main thread I just eat up the gathered input up to a logical game time. It all works, but this set up is using 100% of my CPU. I have two cores, and its going up to 100% while running my game.

I have checked with other games to see if they do that too. For example Skyrim and Doom 3 seem to be fine with just over 60% CPU.

Is it acceptable for a game that uses multi-threaded input to use up 100% CPU? If not, what are some tricks such games use to lower cpu usage by the input thread?


texts: What include first if I want to comply IWYU(Include-What-You-Use) in Unreal Engine 4?

texts:
I read this article. https://docs.unrealengine.com/latest/INT/Programming/UnrealBuildSystem/IWYUReferenceGuide/index.html

It says "IWYU mode is enabled by default for the Engine and Engine plugins." So, I turned on IWYU mode by adding PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs; to my module. It makes a lot of errors because of ".cpp files include their matching .h files first."

So, my question is,

if some cpp files shares one header files(ex. one header file defines API and several cpp files have implementation), what header file should I include first?
Some Unreal engine file like 'AutomationCommandline.cpp' include "CoreMinimal.h" first. It looks like being against the IWYU rules. If it is, how it can be compiled without error?

Thanks.


texts: "Blinking" graphical bug when rotating shadow matrix

texts:
So, we have implemented Krypton shadows into our code for our 2D game, and it's working beautifully. Only issue is that we're running into a bizarre graphical bug when rotating the shadows with the world on the Z axis.

As of right now, the shadows are perfect, until we get to a 45 + 90n degree (45, 135, 225, ... etc, all the "diagonal" angles). At this diagonal angle, the shadow's collapse on the X or Y axis, causing a "blink" effect. We are unsure if this is something inherent with rotating matrices (which Krypton uses) that needs to be worked around, or if this is a bug related to Krypton (and whether or not it can be worked around).

Video Example Of Bug on Youtube

You can find our draw code below. The bool "useFakeFPSPerspective" is used to display this rotating perspective, which has the graphical bug. Our normal perspective does not come across this issue, as it has a fixed angle.

protected override void Draw(GameTime gameTime) {
        //Create a world view projection matrix to use with krypton.
        var world = Matrix.Identity;
        var viewVector = new Vector3(graphics.PreferredBackBufferWidth / 2, -graphics.PreferredBackBufferHeight / 2, 0f) * -1f;
        viewVector.X = -player.LevelPosition.X;
        viewVector.Y = player.LevelPosition.Y;
        var view = Matrix.CreateTranslation(viewVector);

        Matrix? rotateZ = null, shift = null;
        if (useFakeFPSPerspective) {
            var pos = player.Size / 2f;
            viewVector.X -= pos.X;
            viewVector.Y += pos.Y;
            view = Matrix.CreateTranslation(viewVector);

            viewVector.X = pos.X;
            viewVector.Y = -pos.Y;
            shift = Matrix.CreateTranslation(viewVector);

            var mouseState = Mouse.GetState();
            rotateZ = Matrix.CreateRotationZ((float) mouseState.X / -90); //rotates on Z axis (which points "outward", instead of up/down or left/right)
        }

        var projection = Matrix.CreateOrthographic(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight, 0f, 1f);

        //Assign the matrix and pre-render the lightmap.
        //Make sure not to change the position of any lights or shadow hulls after this call, as it won't take effect till the next frame!

        var shadowMatrix = view;
        if (useFakeFPSPerspective) shadowMatrix *= (Matrix) rotateZ * (Matrix) shift;
        Krypton.Matrix = shadowMatrix * world * projection;
        Krypton.Bluriness = 3;
        Krypton.LightMapPrepare();

        GraphicsDevice.Clear(ClearColor);

        SpriteBatch.Begin();

        level.draw();