texts: How to organize a fallback system for older GPUs in OpenGL?

texts:
I don't want to make this question too broad or opinion based, but I really need some help about good practices.

The scenario:

I created a particle engine with functions which require at least OpenGL 4.3. But some GPUs don't support this version, so I want to try to implement a fallback system for it.

But it's not only the particle system. There are many features in 3D engines that can't be simply replaced by a different function name. Some features need different logic behind them and it can go quite complex.

What are the best practices to manage fallback rendering in OpenGL?


texts: libgdx - Texture not appearing sometimes

texts:
When I run the App the Ball moves sometimes downwards, but sometimes its not moving. I dont change anything on script.

What I want is the ball should come from top outside of the screen, but when its visible in screen it should get an random xSpeed.

To test it I added first the bomb in the middle of the screen. But as I said the Ball is not showing sometimes. I run the game on my samsung galaxy s6 edge and the ball is there. Then when I run again it's not there.

That's how I coded.

private static final int SPRITE_SIZE = 32; // It has 32px width and height
private static final int SPRITE_COUNT = 4; // there are 4 sprites
private static final float MAX_SPEED = 1f; // maxspeed
private static final float MIN_SPEED = 0.25f; // min speed

private Vector2 position;
private Animation anim;
private Random random;

private float speedX, speedY;

public Bomb() {
    random = new Random();
    int rand = random.nextInt(2);

    TextureRegion tmp = new TextureRegion(Asset.sprites, SPRITE_SIZE * SPRITE_COUNT, rand * SPRITE_SIZE);
    anim = new Animation(tmp, SPRITE_COUNT, 0.75f);

    position = new Vector2((MainGame.WIDTH/2) - (SPRITE_SIZE/2), MainGame.HEIGHT);
    speedX = 0;
    speedY = -MAX_SPEED;
}

public void update(float dt) {
    anim.update(dt);
    if(speedX == 0) {
        if(position.y + SPRITE_SIZE < MainGame.HEIGHT) {
            speedX = random.nextFloat() * (MAX_SPEED - MIN_SPEED) + MIN_SPEED;
    }
    position.add(speedX, speedY);
}

public void render(SpriteBatch sb) {
    sb.begin();
    sb.draw(anim.getFrame(), position.x, position.y);
    sb.end();
}

EDIT: Maybe here's a problem?

Asset.java

public class Asset {
    public static Texture sprites;

    public static void init() {
        sprites = new Texture(Gdx.files.internal("sprite.png"));
    }

    public static void dispose() {
        sprites.dispose();
    }
}

Animation.java

public class Animation {
    private Array<TextureRegion> frames;
    private float maxFrameTime;
    private float currentFrameTime;
    private int frameCount;
    private int frame;

    public Animation(TextureRegion region, int frameCount, float cycleTime) {
        frames = new Array<TextureRegion>();
        int frameWidth = region.getRegionWidth() / frameCount;
        for(int i = 0; i < frameCount; i++) {
            frames.add(new TextureRegion(region, i * frameWidth, 0, frameWidth, region.getRegionHeight()));
        }
        this.frameCount = frameCount;
        maxFrameTime = cycleTime / frameCount;
        frame = 0;
    }

    public void update(float dt) {
        currentFrameTime += dt;
        if(currentFrameTime > maxFrameTime) {
            frame++;
            currentFrameTime = 0;
        }
        if(frame >= frameCount) {
            frame = 0;
        }
    }

    public TextureRegion getFrame() {
        return frames.get(frame);
    }

    public void dispose() {
        for (int i = 0; i < frames.size; i++) {
            frames.get(i).getTexture().dispose();
        }
    }
}


texts: Why are my objects rotating with my camera?

texts:
I am working with this C# library that wraps OpenGL. I am trying to understand why my objects in the scene are rotating as I yaw my camera (view matrix).

Here is an image where I have 4 separate cubes in a row with no spacing.

If I yaw my camera you can see that the cubes have also rotated. Notice the red arrows which point to the side of a cube that is now visible:

I was expecting that these cubes would not rotate. It looked to me as if something in my code is wrong for their model matrix, but I'm not sure I understand what is happening.

Every render frame I am doing this for each cube:

shader["model_matrix"].SetValue(ModelMatrix);

ModelMatrix is calculated as follows, once:

this.ModelMatrix = Matrix4.CreateTranslation(new Vector3(worldX * size, worldY * size, worldZ * size));

world variables are offsets for the position of the cube, and size is just the length. Each render frame my view matrix is being set:

shader["view_matrix"].SetValue(camera.ViewMatrix);

Here is the vertex shader:

uniform mat4 projection_matrix;
uniform mat4 model_matrix;
uniform mat4 view_matrix;

attribute vec3 in_position;
attribute vec3 in_normal;

varying vec3 vertex_light_position;
varying vec3 vertex_normal;

void main(void)
{
  vertex_normal = in_normal;
  vertex_light_position = normalize(vec3(1, 1, 0));
  gl_Position = projection_matrix * model_matrix * view_matrix * vec4(in_position, 1);
}

I have been basing this extended example off of the tutorial here. I am probably missing something basic (I am just starting OpenGL), so thanks for any help in advance!


texts:
In my isometric game the user can draw a line of arbitrary length, and I need to calculate the "unprojected length" of the same line. Users can only draw lines in 6 directions (4 isometric directions and vertically)

How do I calculate the given BLUE line provided I have the given RED line?

Ray/plane intersection seems to be overkill for such a simple calculation. My isometric angles are 30 degrees, exactly as shown in the image below.

Edit: Assuming a 3D object is projected with isometric projection, it becomes a bit smaller in screen coordinates, no? So what would be the original 3D length before "isometric projection"? Since the user is drawing lines on an already "projected" isometric view, the length cannot be the simple length.


texts:
At the moment I have a movement script which moves my player in Bothe directions but it only faces 1 way -
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float moveSpeed = 5f;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Jump();
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
        transform.position += movement * Time.deltaTime * moveSpeed;
    }

    void Jump()
    {
        if (Input.GetButtonDown("Jump"))
        {
            gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, 5f), ForceMode2D.Impulse);
        }
    }

}

How can I make the sprite face the other way when I move west not east?


texts: OpenGL geometry shader 2d rectangle extrusion has weird angles

texts:
I have a geometry shader that extrudes lines to rectangles in 2d (by outputting triangle strips). When the lines are not parallel to the X or Y axis, I'm getting parallelograms instead. Also, when the line is parallel to the X axis, it appears thinner.

Here's what my result looks like, drawing 4 lines at different angles:

Here's the geometry shader:

#version 150 core

layout(lines) in;
layout(triangle_strip, max_vertices = 4) out;
in vec3 Color[];
smooth out vec3 FColor;

void main() {
  vec3 g1 = gl_in[0].gl_Position.xyz;
  vec3 g2 = gl_in[1].gl_Position.xyz;
  vec3 v1 = normalize(g1 - g2) * 0.1;
  vec3 v2 = normalize(g2 - g1) * 0.1;

  FColor = Color[0];
  gl_Position = vec4(-v2.y + g1.x, v2.x + g1.y, 0.0, 1.0);
  EmitVertex();

  FColor = Color[0];
  gl_Position = vec4(v1.y + g2.x, -v1.x + g2.y, 0.0, 1.0);
  EmitVertex();

  FColor = Color[0];
  gl_Position = vec4(v2.y + g1.x, -v2.x + g1.y, 0.0, 1.0);
  EmitVertex();

  FColor = Color[0];
  gl_Position = vec4(-v1.y + g2.x, v1.x + g2.y, 0.0, 1.0);
  EmitVertex();

  EndPrimitive();
}

To test out the calculation, I ran the same set of vertices through the same calculation in GLM, took the results times 10.0 and plotted them using a web tool. Here's what I got:

So it looks to me like the basic calculation is correct. Can anyone help me understand what I'm doing wrong?


texts: How to create terrain made of small tiles?

texts:
The terrain in my game must be created using tiled assets. I have unique textures for each tile (all with the same height and width that can be used to compose the terrain) and the information of each map is baked in binary files; these binary files contains each tile height and texture.
I'm thinking about creating the terrain at runtime (or create a tool to bake the terrains in unity's proper formats). Each tile would be an mesh composed by 2 triangles. This way I can represent individually each tile and associate a unique tile texture for each tile. My concerns is about performance as it will end up with several different meshes just for the terrain.
Am I thinking in the right direction? Is there other better way to implement a tiled terrain like this in Unity3d?


texts: Anyone know of an online resource with spritesheets from classic games?

texts: I'm looking for spritesheets for classic retro games, and old home computer games (c64, amiga etc.) Does anyone know of a source online?


texts: AABB Sweeping, algorithm to solve "stacking box" problem

texts:
I'm currently working on a simple AABB collision system and after some fiddling the sweeping of a single box vs. another and the calculation of the response velocity needed to push them apart works flawlessly.

Now on to the new problem, imagine I'm having a stack of boxes which are falling towards a ground box which isn't moving:

Each of these boxes has a vertical velocity for the "gravity" value, let's say this velocity is 5.

Now, the result is that they all fall into each other:

The reason is obvious, since all the boxes have a downward velocity of 5, this results in no collisions when calculating the relative velocity between the boxes during sweeping.

  Note: The red ground box here is static (always 0 velocity, can utilize spatial partitioning ), and all dynamic > static collisions are resolved first, thus the fact that the boxes stop correctly at this ground box.

So, this seems to be simply an issue with the order the boxes are sweept against each other.

I imagine that sorting the boxes based on their x and y velocities and then sweeping these groups correctly against each other may resolve this issues.

So, I'm looking for algorithms / examples on how to implement such a system.

The code can be found here: https://github.com/BonsaiDen/aabb

The two files which are of interest are box/Dynamic.lua and box/Manager.lua.

The project is using Love2D in case you want to run it.


texts: Anti-cheat Javascript for browser/HTML5 game

texts:
I'm planning on venturing on making a single player action rpg in js/html5, and I'd like to prevent cheating. I don't need 100% protection, since it's not going to be a multiplayer game, but I want some level of protection.

So what strategies you suggest beyond minify and obfuscation?

I wouldn't bother to make some server side simple checking, but I don't want to go the Diablo 3 path keeping all my game state changes on the server side.

Since it's going to be a rpg of sorts I came up with the idea of making a stats inspector that checks abrupt changes in their values, but I'm not sure how it consistent and trusty it can be.

What about variables and functions escopes? Working on smaller escopes whenever possible is safer, but it's worth the effort?

Is there anyway for the javascript to self inspect it's text, like in a checksum?

There are browser specific solutions? I wouldn't bother to restrain it for Chrome only in the early builds.


texts:
Are there any elegant soloution to generate a simple-six sided cube, where each cube is made out of more than one face? The method I have used ended up a horrible and complicated mess of logic that is imopssible to follow and most likely to maintain. The algorithm should not generate reduntant vertices, and should output the indice list for the mesh as well.

The reason I need this is that the cubes vertices will be deformed depending on various factors, meaning that a simple six-faced cube will nto do.


texts: Flixel: Is it possible to use a spritesheet for FlxButtonPlus?

texts:
I'm trying to change the graphic on a FlxButtonPlus. I want to get the graphic from a spritesheet. However, if I try the ' regular' way (make an animation and play it), it refuses to use just the part of the spritesheet I want and instead insists on showing the complete spritesheet.

Creator of the sprite:

public function ButtonSprite(c:int){
    loadGraphic(ImgButtons, true, false, 30, 80);
    addAnimation("static", [c]);
    play("static");
}

How I try to add it to the button:

currentButton = new FlxButtonPlus(30, 80, playLevel, [0], "Unlimited", buttonWidth * 3, buttonHeight);
var sprite = new ButtonSprite(1);
currentButton.loadGraphic(sprite, sprite);

Thanks!


texts: Libgdx can't read .ttf file when running Android configuration

texts:
Firstly, I am aware that a similar question was asked some time ago that went unanswered. Currently, it has multiple upvotes but no answer.

The error

com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: data/font/font1.ttf (Internal)
...
Caused by: java.io.FileNotFoundException: font/font1.ttf

occurs when I use the class FreeTypeFontGenerator provided by Libgdx as a extension to use freetype fonts(link). This is the line in my project that caused error:

FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("font/font1.ttf"));

I can be fairly certain that my path to the .ttf is correct, as the desktop configuration runs perfectly, showing the font as desired.

My guess: I didn't include the freetype extension when creating this libgdx project. When following the tutorial to include it (that is, adding the freetype dependencies in build.gradle), something somehow went wrong. But even this is not convincing enough.

build.gradle:

project(":desktop") {
    apply plugin: "java"

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
        compile "com.badlogicgames.gdx:gdx-tools:$gdxVersion"
        compile "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-desktop"

    }
}

project(":android") {
    apply plugin: "android"

    configurations { natives }

    dependencies {
        compile project(":core")
        compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86_64"
        compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86_64"
        compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-armeabi-v7a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-arm64-v8a"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86"
        natives "com.badlogicgames.gdx:gdx-freetype-platform:$gdxVersion:natives-x86_64"

    }
}


texts: How to enable geometry shader in OpenGL 4.2?

texts:
I'm porting my Direct3D-based engine to OpenGL and I'm using geometry shaders for rendering text characters (basically, textured billboards).

D3D version works fine, but in OpenGL mode it gives only a flickering point right in the center of the screen.

It seems that somehow the geometry shader stage is not enabled (in AMD GPUPerfStudio the box, representing GS stage, is grayed-out).

I tripple-checked the OpenGL back-end and the shader code but couldn't find any mistakes.
Maybe, I'm missing something.

Below is the source code of the relevant shaders:

Vertex shader:

in vec4 in_xy_wh;
in vec4 in_tl_br;   // UVs for top left and bottom right corners
out vec4 v_xy_wh;
out vec4 v_tl_br;
void main()
{
    v_xy_wh = in_xy_wh;
    v_tl_br = in_tl_br;
}

Geometry shader:

layout(points) in;
layout(triangle_strip, max_vertices=4) out;

in vec4 v_xy_wh[];
in vec4 v_tl_br[];  // UVs for top left and bottom right corners

out vec2 v_uv;

void main()
{
    vec2    pos = v_xy_wh[0].xy;
    float   width = v_xy_wh[0].z;
    float   height = v_xy_wh[0].w;

    vec2    tl = v_tl_br[0].xy;
    vec2    br = v_tl_br[0].zw;

    gl_Position = vec4( pos.x, pos.y, 0.0f, 1.0f );
    v_uv = vec2( tl.x, tl.y );
    EmitVertex();

    gl_Position = vec4( pos.x + width, pos.y, 0.0f, 1.0f );
    v_uv = vec2( br.x, tl.y );
    EmitVertex();

    gl_Position = vec4( pos.x, pos.y - height, 0.0f, 1.0f );
    v_uv = vec2( tl.x, br.y );
    EmitVertex();

    gl_Position = vec4( pos.x + width, pos.y - height, 0.0f, 1.0f );
    v_uv = vec2( br.x, br.y );
    EmitVertex();

    EndPrimitive();
}

Fragment shader:

in vec2 v_uv;
out vec4 v_color;

uniform sampler2D   s_font;

void main()
{
    vec4 color = texture( s_font, v_uv ).rgba;
    if( color.w < 1.0/255.0 ) {
        discard;
    }
    v_color = color;
}

I've added the "#version 420 core" preamble to each shader.
I know I shouldn't use the glProgramParameteriEXT function to define GL_GEOMETRY_INPUT_TYPE_EXT, GL_GEOMETRY_OUTPUT_TYPE_EXT, GL_GEOMETRY_VERTICES_OUT_EXT,
because these parameters are specified in the geometry shader (which is core in OpenGL 4.2).

EDIT:
My mistake was incorrect usage of glVertexAttribPointer (wrong value of the the last parameter).
Thanks for all the answers and sorry for your wasted time!


texts: Input.mousePosition gives a NullReferenceException

texts:
I'm trying to Add raycast shooting to my player but when I get the Vector2 mouse position it give this error

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

This is my code

   Vector2 mousePosition =
         new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                     Camera.main.ScreenToWorldPoint(Input.mousePosition).y);

How can i fix this ?


texts: is there a formula to know how many enemies i can place before jumping character?

texts:
My game is very similar to the hidden game in chromes web browser. I have a character that needs to jump over incoming enemies. Is there any way i can know when to send an incoming enemy? Some of the factors to take in to account i guess are the speed of enemies, height of jump, speed of jump, and dimensions of bitmaps (that represent character, and enemies).

Thanks


texts: What happen if I try to run OpenGL 4.4 code on an unsupported graphic card?

texts:
I'm learning OpenGL because I'd like to build my own engine.
I'd like to know what happens if I try to run OpenGL 4.4 code (the latest version at the moment of writing) on an unsupported graphic card ? (I mean for example a graphic card that support up to 4.1 OpenGL). Does it fails even to start ? or, it start but fails to render ?

Thank you very much.


texts: Drag & Drop with a verifying system with BoxCollider2D

texts:
I'm really struggling to create a decent Drag & Drop system. The game idea is that the player would drag images (at the left side of the screen) to different slots (at the center) to create an allegorical car, and then the game would give a score to what the player created.

But the problem is: the gameObjects have BoxCollider2D components (both of them have the IsTrigger on) and they don't interact with each other. The item slot doesn't detect that something has been dragged into it and which image was dropped.
This is the script of the gameObjects that are being dragged:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class DragDrop : MonoBehaviour, IPointerDownHandler, IPointerClickHandler,
                    IPointerUpHandler, IPointerExitHandler, IPointerEnterHandler,
                    IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler {

[SerializeField] private Canvas canvas;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;
float spawnPositionX;
float spawnPositionY;
float spawnPositionZ;
float scaleX;
bool dragging = false;

private void Awake() {

    rectTransform = GetComponent<RectTransform>();
    canvasGroup = GetComponent<CanvasGroup>();
    spawnPositionX = transform.position.x;
    spawnPositionY = transform.position.y;
    spawnPositionZ = transform.position.z;

    scaleX = transform.localScale.x;
}

public void OnBeginDrag(PointerEventData eventData) {

    Debug.Log("Drag begin!");
    canvasGroup.alpha = .6f;
    canvasGroup.blocksRaycasts = false;

    dragging = true;
}

public void OnDrag(PointerEventData eventData) {

    Debug.Log("Dragging.");

    Vector3 screenPosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, canvas.planeDistance);
    Vector3 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
    transform.position = worldPosition;
}

public void OnEndDrag(PointerEventData eventData) {

    Debug.Log("Drag ended!");
    canvasGroup.alpha = 1f;
    canvasGroup.blocksRaycasts = true;

    dragging = false;
}

public void OnDrop(PointerEventData eventData) {

    Debug.Log("OnDrop");
}

public void Update() {

    if (dragging) {
        if (Input.GetKeyDown(KeyCode.R)) {
            scaleX = -scaleX;
            this.gameObject.transform.localScale = new Vector3(scaleX, 1f, 1f);
        }
    }
}

void OnTriggerEnter2D(Collider2D other){

    Debug.Log("Test 1.");
    if(other.gameObject.tag == "GameSlot"){
        Debug.Log("Test 2.");
        GameObject iconClone = Instantiate(gameObject, new Vector3(spawnPositionX, spawnPositionY, spawnPositionZ), Quaternion.identity, GameObject.FindWithTag("Canvas").transform);
    }else{
        Destroy(this);
    }
}

And this is the script of the slots which the images will be dragged into:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class ItemSlot : MonoBehaviour, IDropHandler {

public void OnDrop(PointerEventData eventData) {

    Debug.Log("OnDrop");

    if (eventData.pointerDrag != null) {

        eventData.pointerDrag.GetComponent<RectTransform>().anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
        gameObject.GetComponent<Image>().color = new Color32(255,0,0,100);

    }
}

How do I solve this problem?


texts: Moving a sprite in XNA/C#, using vectors

texts:
I'm currently looking into XNA game development with the C# language.

I have two classes: the main game handler and a "sprite" class. Following is some basic pseudo-code which I hope adequately describes the issue.

Game.cs

class game {
  sprite the_sprite;
  void update(time) {
    var mouse = mouse.state
    if(mouse.clicked) { this.the_sprite.moveTo(mouse.x, mouse.y) }
    this.the_sprite.update(time)
    base.update(time)
  }
}

Sprite.cs

class sprite {
  vector2 location;
  vector2 move_to;
  void moveTo(x, y) { this.move_to = new vector2(x, y) }
  void update(time) {
    if(this.location.x > this.move_to.x /* (or less than) */) {
      // adjust location.x
    }
    if(this.location.y > this.move_to.y /* (or greater than) */) {
      // adjust location.y
    }
  }
}

Basically: when the user clicks somewhere in the game window, the x and y coordinates of the mouse are taken, and the game object will move towards that location over a period of time.

Well... the code works, but it's ugly, and objects don't move directly towards the object (instead, it's diagonal movement, followed by single-axis movement). I'm guessing there are some mathematical functions I can use, but I honestly haven't a clue where to get started. Any suggestions?


texts: Ortho projection of 3D points with a vector

texts:
I have 3D points and I need to make an 2D orthographic projection of them onto a plane that is defined by the origin and a normal n. The meaning of this is basically looking at the points from the top (given the vertical vector). How can I do it?

What I'm thinking is:

project point P onto the 3D plane: P - P dot n * n
look at the 3D plane from the "back" in respect to the normal (not sure how to define this)
do an ortho projection using max-min coordinates of the points in the plane to define the clipping

I am working with iOS.


texts:
I'm having a hard time getting a UI to work and I'd love some advice on what I'm doing wrong.

I have a GameObject (P1 below) which holds a hand of cards (a script containing an array of GameObjects). Everything instantiates correctly from prefabs.

I followed this drag-and-drop example to create a draggable script applied to each prefab. Initially, I had the DropZone script from the tutorial video applied to the PlayMat object and had no problem (in tutorial video #2 it adds a Debug.Log message to the DropZone script to indicate when a successful drop has taken place.

Canvas1 and Canvas2 (same X scale as PlayMat but both are half the Y scale..imagine a card game field like Yu-Gi-Oh so Canvas1 is for Player 1 to place cards and Canvas2 is where Player 2 places cards) have coordinates that place them ABOVE the PlayMat but when I attempt a drop, only the PlayMat object registers. How can I make only Canvas1 or Canvas2 register the raycast hits?

Heirarchy as follows:

 Main Camera
 Canvas
     Canvas1
     Canvas2
     PlayMat (RectTransform with Canvas Renderer and holds the background image)
 EventSystem
 P1


texts:
First of all asking before asking this question I have already read following post for the clearance of my mind.

Sprite Renderer

Texture 2D

I want to change my background texture as per device aspect ratio detection. For this purpose I have following code:

var newSprite : Sprite;

function Start () {
      GetComponent(SpriteRenderer).sprite = newSprite;
}

Or another way to load sprite is :

Sprite myFruit = Resources.Load("fruits_1", typeof(Sprite)) as Sprite;

Using above code I can able to load new sprite as per my requirement. But I want to reduce following disadvantage from this.

At present basically I set background sprite of 960 x 640 for iPhone 4 and its get loaded. After that I change my background sprite to 2048 x 1536 as I detect the device with iPad Retina display. So another texture get loaded. I want this process to happen single time so how to manage sprite texture in correct way.

Also thanks for your attention towards this question.


texts: ELO Rating System & Multiple Games Against the Same Player

texts:
I've decided to use the ELO rating system for my chess-like strategy game.

I've implemented the algorithm but I don't really understand it completely (I'm not a maths person)...

I've decided to give starting rank of 1000 for new players, and I use 32 as max increase.

Now for my actual question:

Let's say that player A plays hundreds of games against player B, and player A is much better player (or player A has created a dummy account so that he cheats!).

Do I need to take this in account in any way "manually" or does ELO handle this "automatically"? I mean, ultimately the difference between the two players will be so great that the "cheater" gets only +1 to his rank? So he would possibly have to play LOTS of games to cheat/climb up the ladder this way? Am I correct?

I REALLY wouldn't want to disallow the ladder system completely for friend vs friend (invited matches). And I shouldn't need to: even www.chess.com handles this in some way.


texts: Mesh generation for procedural city generator

texts:
I have a programming problem relating to mesh generation for city grids. I've recently created a city grid generator and I've come as far as being able to reliably generate the road mesh for the grid my system spits out. However, now I am stuck with finding a method to generate the lots and spaces in between the roads. Eventually, I want the city grid to have elevation changes and for that, I need to be able to fill in the spaces between the roads.

Here's an example of what I have:

I've looked into triangulation methods like Delauney Triangulation, but the output is unreliable (maybe due to the way I am using it). Here's another example that shows the problem (the black lines are the road mesh, the magenta ones are the Delauney output):

For the most part, the Delauney output follows the mesh when I present it with only the vertices that make up the intersections. However, sometimes, the Delauney triangles overlap the ones from the road mesh (like with the wide road in the center of the image). I am using a port of as2Delauney for Unity and I simply create a list of all the vertices that make up the intersections and then pass it to the Delauney function and I wonder if there is something I need to consider before passing a bunch of points and letting the function sort it out.

Are there any special considerations I need to be aware of when using Delauney for this type of triangulation, or are there any other methods that I could use to create the fill ins for the road mesh?

I've thought about building a function that tries to follow the intersections in clockwise or counterclockwise order until it loops back to the start, but that would lead to infinite loops as some roads are dead ends.

Right now I am not really sure what to look for as I lack terminology and google has yielded no results as to the methods that I could use to generate the fill ins for the road mesh (there is some good stuff on city generation, however not on the mesh part).

Does anyone have any experience with this?

Edit: This is how my system works:

Basically, I use an open list of lines to grow my network and I check the lines against a bunch of constraints. Then I go through each line and I generate intersections for each start and endpoint. So if the end/start is already in my list, I add the other point as a destination for the current intersection.

I end up with a list of custom objects that hold their own position vector and all the position vectors of the intersections it connects to. With this I then create the mesh points for the intersection by checking the cutting points of the lines that make up the sides of the roads, so I have those points at my disposal and i use them to create the triangles for my mesh.

Now I just need to know how to organize them to create the fill ins that span multiple intersections.


texts: When key pressed rotate until lifted if key up smoothly revert to original position and if rotate too far die

texts:
I am trying to have a smooth rotation animation on this hover-car to make it seem more realistic.
I am trying to code it so that if the key a or d is pressed it will rotate to the left and right accordingly. If it rotates too far then it dies and the scene is reloaded. When the keys a or d are lifted then it will smoothly revert back to its original position. I want it to rotate on the x axis of its origin. If you see in the image the scenes axis is z and the axis of origin that points in the direction of that from the vehicle is its x.
Here is the scene with the axis's of the vehicle:

        public int speed = 100;
        public float maxrotation = 30f; //To Set Max Rotation

        void Start()
        {

        }

        // Update is called once per frame
        void Update()
        {
            if (transform.rotation.eulerAngles.x > 0)
            {

                transform.rotation.eulerAngles.x - 1; //there is an error on this line saying "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

            }
            if (transform.rotation.eulerAngles.x < 0)
            {

                transform.rotation.eulerAngles.x + 1; //there is an error on this line saying "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

            }
            if (Input.GetKey(KeyCode.A))
            {
                //Set a rate at which we should turn
                float turnSpeed = speed * Time.deltaTime;
                //Connect turning rate to horizonal motion for smooth transition
                float rotate = Input.GetAxis("Horizontal") * turnSpeed;
                //            //Get current rotation
                //            float currentRotation = gameObject.transform.rotation.z;
                //            //Add current rotation to rotation rate to get new rotation
                //            Quaternion rotation = Quaternion.Euler (0, 0, currentRotation + rotate);
                //            //Move object to new rotation
                //            gameObject.transform.rotation = rotation;
                gameObject.transform.Rotate(Vector3.left * rotate);
            }
            if (Input.GetKey(KeyCode.D))
            {
                //Set a rate at which we should turn
                float turnSpeed = speed * Time.deltaTime;
                //Connect turning rate to horizonal motion for smooth transition
                float rotate = Input.GetAxis("Horizontal") * turnSpeed;
                //            //Get current rotation
                //            float currentRotation = gameObject.transform.rotation.z;
                //            //Add current rotation to rotation rate to get new rotation
                //            Quaternion rotation = Quaternion.Euler (0, 0, currentRotation + rotate);
                //            //Move object to new rotation
                //            gameObject.transform.rotation = rotation;
                gameObject.transform.Rotate(Vector3.left * rotate);

            }
            if (transform.eulerAngles.x > maxrotation)
            {
                Application.LoadLevel(Application.loadedLevel); //kills player and reloads scene
                scorecript.scoreValue = 0; // sets score to zero
            }
            if (transform.eulerAngles.x < maxrotation - (maxrotation * 2))
            {
                Application.LoadLevel(Application.loadedLevel); //kills player and reloads scene
                scorecript.scoreValue = 0; //sets score to zero
            }

        }

<!-- end snippet -->


texts: Unity - Level complete progress bar stops at 75%

texts:
I am trying to build a progress bar that indicates the completion of the current level from 0 to 100% (or from 0 to 1 in probability). I found this example:

https://stackoverflow.com/questions/34960494/distance-from-start-point-to-end-point-in-percentage-in-update

It works, but my progress bar stops at about 75% when i reach the target position and then it drops down. This is my code:

public GameObject player;
public GameObject target;
public Text scoreText;

private float startDistance;
private float currentDistance;

private void Start()
{
    this.startDistance = Vector3.Distance(player.transform.position, target.transform.position);
}

private void Update()
{
    this.currentDistance = Vector3.Distance(player.transform.position, target.transform.position);
    float percentage = 1 - (currentDistance / startDistance);
    transform.localScale = new Vector3(percentage, 1f, 1f);

    this.scoreText.text = string.Format("Score: {0}%", Mathf.Round(percentage * 100f));
    Debug.Log("Percentage Completed: " + (percentage));
}

The player moves by himself towards the target position at constant speed without acceleration. The player can move its character left or right in order to avoid obstacles. This doesn't change the player's speed, it just maneuvers the direction. Maneuvering, I realized the progress sometimes goes beyond 75% and sometimes below. Why is this happening? How to make the progress simply reach 100% when I reach the target position?


texts: How to create spaceship 'ion trails' that can be curved in Unity?

texts:
I'm working on a simple space combat game (single-player) with the goal of having 100+ fighters and capital ships in a single battle.  To keep system requirements down I'm using a minimum of effects.  One that I do wish to include, however, is that of 'ion trails' from the rocket engines of the spacecraft and missiles.  Ideally it would look something like the images below.  The trail won't have to be very long, but I do want it to curve to show the spaceship's path, acting as a visual aid in a dogfight.

My question is, how to implementing such trails efficiently?


texts:
I'm working on a ray-tracer in C++ with an adjustable camera for a university assignment. I'm entirely new with graphics and I'm struggling with one thing.

I have a matrix as a mat4 object (4x4 matrix with each cell saved in a 1D array) that I save in a Camera object that handles transformations of every point in the scene (which is currently just two spheres). Translations seem to be working fine, but when I attempt rotations, things break. The spheres deform, and it only gets worse the more I attempt to rotate the camera.

This is where I set the camera matrix:

mat4 Renderer::setCameraMatrix(const Camera &camera)
{
    mat4 cameraToWorld = mat4(); // Initialise 4x4 matrix.

    // Translation.
    cameraToWorld.cell[3] = camera.pos.x;
    cameraToWorld.cell[7] = camera.pos.y;
    cameraToWorld.cell[11] = camera.pos.z;

    // Rotation.
    cameraToWorld.cell[0] = camera.orientmat.cell[0], cameraToWorld.cell[1] = camera.orientmat.cell[1], cameraToWorld.cell[2] = camera.orientmat.cell[2];
    cameraToWorld.cell[4] = camera.orientmat.cell[4], cameraToWorld.cell[5] = camera.orientmat.cell[5], cameraToWorld.cell[6] = camera.orientmat.cell[6];
    cameraToWorld.cell[8] = camera.orientmat.cell[8], cameraToWorld.cell[9] = camera.orientmat.cell[9], cameraToWorld.cell[10] = camera.orientmat.cell[10];

    return cameraToWorld;
}

This matrix is then used to set the origin and direction of the camera in the world space later on in the code:

vec3 orig = transformpoint(vec3(0), cameraToWorld);
/*...*/
vec3 dir = transformvector(vec3(x, y, -1), cameraToWorld) - orig;
dir.normalize();

The transformpoint and transformvector functions basically multiply a vector v by a matrix M (M.v), except the former takes into consideration translations, and the latter doesn't. Their code can be found here.

The orientmat matrix is calculated from the three separate orientation angles (orient.x, orient.y, orient.z) in this line of code:

cam->orientmat = mat4().rotatexyz(cam->orient.x, cam->orient.y, cam->orient.z);

Using this function:

mat4 mat4::rotatexyz(const float a, const float b, const float c)
{
    mat4 M;
    const float ca = cosf(a), sa = sinf(a);
    const float cb = cosf(b), sb = sinf(b);
    const float cc = cosf(c), sc = sinf(c);

    M.cell[0] = cb * cc, M.cell[1] = -1 * cb * sc, M.cell[2] = sb;
    M.cell[4] = sa * sb * cc + ca * sc, M.cell[5] = -1 * sa * sb * sc + ca * cc, M.cell[6] = -1 * sa * cb;
    M.cell[8] = -1 * ca * sb * cc + sa * sc, M.cell[9] = ca * sb * sc + sa * cc, M.cell[10] = ca * cb;

    return M;
}

(This function basically creates this transformation matrix from the three camera orientation angles.)

I've tried to keep this question as compact as possible but I can provide more code if needed. I'm completely baffled about why I'm getting this kind of deformation on my spheres, and some insight would be invaluable! Thanks.


texts: How can I optimize per-pixel drawing in SDL?

texts:
I've been messing around with C++ the last few days and I'm trying to figure out how to draw the screen pixel by pixel each frame.

It sounded simple enough at first, but then I realized for loops during the games main loop is nothing but a slow mess. How do I safely and with speed show visual effects?


texts:
Background

Our team is creating an adventure platformer, and I have been tasked with creating a Save Game system.

Our game features the usual progression systems, and is relatively linear.

Approach

I have began my approach by using the EMS Easy Multi-Save plugin for Unreal.

Problem

We have a 'Switch' system:

Player takes cube to switch.
cube gets used by switch
switch can now be activated.

In stage 2, where the cube is used by the switch - the actor for the cube is destroyed in Unreal, and the switch's model is changed to one with a switch.

The EMS plugin does not provide plug-and-play functionality for keeping track of destroyed actors, which means I must do this myself.

Example problem scenario

Player approaches area with switch and cube.
Player saves game (cube present and switch deactivated)
Player picks up cube and takes to switch (cube destroyed and switch activated)
Player loads prior save game
Scene reloads with switch in the correct state, however the cube is no longer present (it has been destroyed by Unreal and is no longer tracked by EMS)

Problem solving approach

Reading around, I have been given the idea of creating my own class that keeps track of destroyed actors when they are destroyed.

This class can be saved by EMS, and then can reload these destroyed actors if needed when a game is loaded.

Question

There is a lack of real advice for the task at hand here, so I wanted to come here and ask for people's advice and opinions on the best approach to making Destroyed Actors within Unreal compatible with Save Games.


texts: What type does one cast the result of "get_function_address" to in order to call the function within a C++ DLL?

texts:
According to the game maker documentation for dll manipulation:

  get_function_address('function_name')

  Returns the address of a GameMaker function. This can be passed to
  DLL's so the can call directly into GameMaker.

  This feature is unsuported, so care must be taken when using this
  function.

  Please Note: These functions use Delphi 2010 PASCAL calling convention and string formats.

Let's assume one writes a C++ dll and wants to use those function pointers to make game maker function calls within the dll code.

What does one cast the function pointer to? I am familiar with passing a C function pointer to a C++ dll (it is blatantly obvious what you cast the pointer to; the same thing as what you would within the C code). However, I do not know what I would cast functions to coming from game maker. I imagine it is a relatively "simple" thing to do once you know the magic dance. It just doesn't say anywhere what to do.

I think the page might be trying to tell me that this is equivalent to passing a pascal function pointer to a C++ dll. I don't really know. I can't be the only guy with this problem.


texts:
I want to know how does MMO flash games work, for example: Dofus and Club Penguin.

I want to know if by ony using Adobe Flash and ActionScript you can do MMO games, or if there is other way to work with ActionScript and Flash beyond Adobe Flash.


texts: Planning to start a right game design pattern

texts: I'm planning start a game development (I did develop many promo games but now I will start my games with the best code design patterns). I will use QT Creator with C++14, OpenGL and some physical engines. Will I going on right direction? I will use it to compile in multiple plataforms (PC/MAC/iOS/Android)


texts: Unity Facebook "An access token is required to request this resource."

texts:
I have installed Facebook SDK 7.6 for Unity 5.3. It is fine with login and logout stuff things but I am having a problem when it comes to use FB.API. I want to be able to fetch players' profile pictures and names for my multiplayer game project. Each client has other's facebook profile id but I cannot use those IDs on Graph API I guess. What is the way of getting such public information using Facebook SDK.

FB.API("/" + facebookID + "?fields=name", HttpMethod.GET, OnNameReceived);


texts: UNITY : I want to make my UI text fade in after 5 seconds

texts: I know this question has been asked and asked but none of the topics i visited gave me an answer. I'm making a game programmed in c# where you control a boat and i want my UI to appear smoothly by fading in after X seconds. May someone help me?


texts: How does matrix based game physics (collision detection & response) work?

texts:
I'm familiar with how to do collision detection and response using shape intersection tests, the separating axis theorem, and by using MPR and GJK with minkowski sums and support vector defined shapes.

I know that there is another way to do collision detection and response using matrices, but I don't know anything about it.

Can anyone explain to me the basics of how that works, or link me to some resources? I've been unable to come up with the right terms to ask google apparently.

Thanks!


texts:
I am making a civilization style game in Unity. The game uses square tiles and has a 2d sprite style. I am currently implementing a border system like in civ4 where a line is drawn around you civilization's borders, but I cannot find a way to create the correct sprites to draw the border.

My first thought was to have a sprite corresponding to each neighbor, the sprite would toggle on if the tile it is over is in the bordered area and the corresponding neighbor is not. This would work but It would require 8 (one for each neighbor) sprite renderers per tile and I assume that would be pretty inefficient.

I thought of making a separate sprite for each configuration to cut it down to one sprite renderer per tile but that would require 2^8 sprites which just is not feasible.

I also thought that maybe I should stick to the first idea but only instantiate or move sprite renderers to where they are needed which would greatly reduce the amount of sprite renderers used at once. This seems like my best option but it seems unnesicarily complicated and still pretty inefficient.

I do not know of any simple way to dynamicaly draw sprites to fit a pattern, so it seems I am stuck with one of these solutions. Does anyone know of a better way to handle this?


texts: How do I generate a mipmap for a texture loaded from a stream?

texts:
I am loading a Texture2d from a stream:

public static Texture2D GetTexture(GraphicsDevice dev, System.Drawing.Bitmap bmp) {
    Texture2D texture;
    using (MemoryStream s = new MemoryStream())
    {
        bmp.Save(s, System.Drawing.Imaging.ImageFormat.Jpeg);
        s.Seek(0, SeekOrigin.Begin);
        texture = Texture2D.FromStream(dev, s);
    }

    return texture;
}

I want to generate a mipmap for the texture, as my texture looks bad when viewed from afar. How do I do this?


texts: I'm trying to implement collision detection using the latest JiglibX. I am working off of this example. I chose creating a callback. I'm trying to detect a collision only once. When the object falls through, the callback is invoked multiple times, not only once. Is there any way how to ignore other calls? Thanks for advice.


texts: Spider physics to patrol on platform smoothly when changing direction

texts:
I have a 3 tile wide platform. I want my spider to hang from the ceiling and patrol this platform left and right.
I have dx property for velocity. I want a physics code that shows how to achieve this.
I tried this but it is too harsh:
  if (dx < 0 &&
      !base.isSolid(-16, -1)) {
    dx *= -1;
  } else if (!base.isSolid(16, -1)) {
    dx *= -1;
  }

What I want spider is to slow down on edges change direction and speed up.


texts: I want to be able to draw single lines inside Vulkan but the only way I have managed to achieve this so far is by drawing a triangle with two of its points that ocupuy the same point in space. Is there a way to draw lines inside Vulkan and also change their width? I know I can change line width when I set the polygon mode in the rasterizer to VK_POLYGON_MODE_LINE and then set the lineWidth option, but I need to be able to do it whilst rendering all other 3D objects with VK_POLYGON_MODE_FILL enabled.


texts:
I'm making a game using in C# and Javascript that uses a map which has tiles, corners and borders. Here's a graphical representation:

I've managed to store tiles and corners in memory but I'm having trouble getting the borders structured.

For the tiles, I have a Map Width * Map Height sized array. For corners I have (Map Width + 1) * (Map Height + 1) sized array.

I've already made up the math needed to access corners from a tile, but I can't figure out how to store and access the borders from a single array.

Tiles store their type (and other game logic variables) and via the array index I can get the X and Y coordinates. From this tile position it is possible to get the array index of the corners (which store the Z index).
The borders will store a game object and accessing corners from only border info would be also required.

If someone even has a better way to store these for better memory and performance I would gladly accept that.


texts: Parallax camera is not independent from the stage camera

texts:
I have a weird camera problem that I can't solve! I add my actors to the main stage and use its camera too. Actors are constrained within the screen viewport.
I also have a second camera that I use for the parallax background. I check for touchDragged and touchDown to move the actor to that position. So I do:
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    getStage().getCamera().unproject(touchPosition.set(screenX, screenY, 0f));
    player.moveTo(touchPosition);

    return false;
}

I can pan the parallax camera, and I do:
public void panBy(float x, float y)
{
    panTo.set((float)MathHelper.round(position.x + x, 0), (float)MathHelper.round(position.y + y, 0), 0);
    panning = true;
}

@Override
public void update() {
    if (panning) {
        position.x += (panTo.x - position.x) * panLerp;
        position.y += (panTo.y - position.y) * panLerp;

        Vector3 pos = new Vector3((float)MathHelper.round(position.x, 0), (float)MathHelper.round(position.y, 0), 0);

        if (pos.epsilonEquals(panTo)) {
            position.set(pos);
            panning = false;
        }
    }

    super.update();
}

The drawing is done:
public void draw(Batch batch)
{
    //Start batch
    batch.setProjectionMatrix(parallaxCamera.combined);
    batch.begin();

    background.draw(batch, 1f);

    //End batch
    batch.end();
}

Actors are handled by the stage right after the above draw call.
The above work fine individually. However when I pan and drag the actor the parallaxCamera follows the actor too. I the parallaxCamera to be totally independent and just keep scrolling.
Why do I have this behavior?


texts:
I searched a lot about this problem. I found many answers here in Stack Exchange but none of them really answers when positions for objects get updated.

For a game with fixed size map and that has all the time:

200+ moving objects with different sizes (bullets, players, NPCs, etc.)
100+ static objects with different sizes (obstacles, health packs, etc.)

I am looking for an efficient way to do collision detection. Here is the pseudo code:

in each game loop (15 ms):
   collect movement commands and apply force on objects of those commands
   loop with very small physics time steps (0.1 ms):
      for object in movingObjects:
         get objects that might collide with current object   // --> 1
         check if any collision occurs
      for object in movingObjects:
         update position of object (based on command collected) // --> 2

So:

I get the objects that might collide with given object. It is done using a data structure like quadtree or spatial hashing grid (or something else that makes more sense).
Object's position is updated. Now, how do I inform the data structure that this object's position is updated? I don't want to remove and insert. That is not efficient at all.

I feel like quad tree and spatial hash implementations all over the internet are avoiding this problem.

I would also appreciate if you tell me my pseudo code above is problematic. I have the feeling this uses too much CPU.


texts:
I've been experimenting with Ray Wenderlich's tutorial about masking sprite using shaders with cocos2D 2.0.

It works pretty well but now I'd like to rotate the mask independently of the masked texture.

Does anyone have any idea about how to achieve it ?


texts: How do I remove unwanted areas while keeping the animated keyframes and wav in sync?

texts:
I recorded a motion-capture along with voice as fbx and wav. How do I remove unwanted time periods while keeping the animated keyframes and wav in sync?

3DS MAX 2012 is being used. Standard plugins are being used.

Example: I want to remove long pauses manually in which the character neither moves nor speaks.

See this, the crossed areas should be removed:


texts: Is there such thing as a hybrid View that combines SurfaceView and GridView in Android?

texts:
I am trying to develop several Android games that work on a grid system. I will need to update the game surface frequently, so using a GridLayout does not seem to be a good option. The frequent updates to the game surface would be similar to what you see in Plants vs Zombies: the user can interact with parts of the grid, but the sprites representing the computer opponent will always be moving until the level ends.

I want to sublcass SurfaceView but give it many of the built-in properties of a GridLayout (ex. I want to allow the user to drop a game object in a grid cell and have that object start animating within the bounds of the grid cell, so I would want row and column indexes built in to my custom SurfaceView) but that's a lot of work.

Do you now if something like this already exists?

Is it better to just use a "normal" SurfaceView and somehow keep track of where on the SurfaceView the grid lines should fall, maybe using a HashMap or something to track the vertices of all the grid cells? That seems like a lot of work and I don't want to reinvent the wheel if I don't have to.

I'm looking for design device or recommendations on free libraries (*.jar) that I could use to accomplish this goal efficiently. I'm coding in plain old Android Studio so no Unity access :(


texts: How to draw a 3D world with lines, more like a sketch drawing or cartoon

texts:
Consider making an ink drawing, with no shading and all lines having equal weight - such as you see in a strip comic like Dilbert. This represents an active 3 dimensional world, but objects do not have textures, yet you don't see tessellated triangles either.

For the sake of an example consider drawing the surface of the moon. The lines you might draw would be along the top edge of hills, down to where they meet the general level of the surface. Behind those you would do the same for larger hills, into the distance, and behind that what was visible of the horizon. For craters, you might draw a near circle for the outer edge, and partly masked, a circle for the lower edge. Boulders would have a line around the edge, and along major visible edges. The astronauts would have a line along their outer edge, and along major features of their space suit.

I'm an experienced programmer but new to 3D programming. I can't offhand think of a game that looks like this -- has it been done? And how would one do it? Two problems come to mind -- finding the significant edges, and drawing it. Would it need an "engine" coded from matrices up, based on lines, rather than a regular 3D engine?


texts:
When does a game version change

from x.x.x.x to x.x.x.x+1 like from 1.0.0.0 to 1.0.0.1

or from x.x.x.x to x.x.x+1.x ?

or from x.x.x.x to x.x+1.x.x ?

or from x.x.x.x to x+1.x.x.x ?

Should the first game version be 1.0.0.0 or 0.0.0.1?


texts:
I'm trying to submit my app for review with publish_action.

I keep getting the following error:

"It looks like you haven't made any API requests to access content with the publish_actions permission in the last 30 days."

I'm publishing posts to the users' feed with Facebook SDK for Unity.:

 FB.Feed(link: LinkToApp);

I've filled all the necessary fields.

I posted both from the Graph and from an iOS device and I still get the same error when I try to submit for review.

What is missing?


texts: Why is my color on my obj not showing in Unity!

texts: I've been trying to import my full-color obj files to unity for a while now, but I can't get them to be in color. All of the colors show up in Meshlab, but not in Unity. All of the youtube videos I have watched have said that I need some sort of texture file but my obj doesn't have one. It is just the obj and it somehow has color in Meshlab. Is there some sort of setting I need to change in Unity? If I need a texture file for it to work, is there a way I can extract the texture file(s) from the obj?


texts: HTML5 multi-player game data/event validation best practices

texts:
I'll start by saying that I am fully aware that this question might seem subjective at first, but I'll try and provide a specific test case scenario for it to be a clear question about validating the data received from 2 multiplayer game clients.

Scenario

Imagine we have a multi-player Tower Defense (TD) game. And let's assume that the game is built using HTML5 Canvas, Javascript and a multi-threaded web server, for example, Tornado running in the back-end. And in this scenario both of the players have an option to place a turret anywhere they want.

After a turret is placed, a bunch of enemies are released from both sides and move in a straight line towards the other side.

As soon as an enemy reaches turret range, we can assume that it is destroyed in 1-5 shots. If it takes more than that, the enemy safely passes to the other side.
Now, my problem lies in the fact that usually I would do all the validation server-side, but it becomes increasingly difficult to do, because I would need to simulate every step of the game.

Instead, I would like to depend on the event data (enemy destroyed/enemy gets safe passage) received from both clients.

Question

The main question then is this:

What is the best and hopefully easiest way to implement these sorts of checks and would there be anything prohibiting me from continuing with the development using HTML5, Canvas and Javascript?


texts: GestureListener's fling method doesn't get called

texts:
I'm using SimpleGestureDetector from the libgdx-users Wiki as my InputProcessor. I set it in the created() method:

Gdx.input.setInputProcess(new SimpleDirectionGestureDetector(charController));

charController is my class which implements the DirectionListener interface defined in the SimpleDirectionGestureDetector class and it is responsible for moving the player character. However the character doesn't change direction when I'm performing a fling action in any direction. I've checked and the fling() method in the SimpleDirectionGesture class doesn't get called and I have no idea why, since everything seems good. What am I doing wrong?


texts: Handling mouse input depending on selected unit and clicked tile

texts:
I am making a turn-based tactical game (think something like X-Com) and I am currently trying to figure out how to handle mouse input in a clean way without a mess of if-statements.

I have a lot of variables that come into play and that changes what happens when you click a tile in the game.

For example: if the currently selected unit is a player controlled unit and the tile you click is within that units movement range, I want to queue up a move action. If the clicked tile contains another player character I want to select that one instead, but if it contains an enemy I want to select the enemy or attack it if the player is adjacent.

So basically what happens when you click depend on selectedUnit, clickedTile, clickedTile.getUnit().getType(), and if the selected units tile is a neighbour to the clicked tile.

Is there a cleaner way to handle this than a mess of if-statments? I am using Java and Libgdx if that matters, but I am guessing this is mostly a design question.


texts: MonoGame Point filtering movement appears Choppy/Jerky

texts:
When you move a sprite that is drawn using point filtering with a decimal number, example : 0.1 pixel or 100 * deltaTime (1.6) the movement appear choppy/jerky because it jumps from pixel to pixel. How would I go about doing to make the movement smooth?

  please don't answer : linear filtering because I get some issues with my map then


texts: TTF fonts are being converted to image in CPU or GPU?

texts: Once I use a TTF font, when they are being converted to images to be rendered? Does CPU or GPU do the conversion? How heavy is that operation?


texts: increasing speed of sound as player approaches

texts:
I am trying to create a sound that increases in speed as the player gets closer to the object. The sound is just a single 'ping' and will increase in frequency as we approach, once we are on top of it, it should play a different sound. I can't seem to get it to work. Here is what I've done in blueprints:

I'm not extremely experienced with Blueprints and I have almost no experience with working with sound in it. From my understanding, the blueprint should be measuring the distance between the object and the player, dividing it by .5, and then returning the sound at that speed.

Currently, I'm getting no sound whatsoever.


texts: Stop player following cameras cameras direction

texts:
Okay I'm not going to go to much into it but this is what I need my script to do. The way I have my controller set up is that the camera looks to the side of the player a little bit. I use this for aiming attacks, bullets and what not. The problem is that it follow the camera when it looks up causing my character to slightly jump ever time I aim and look up. So i want the player to move with the camera while ignoring its y axis. and i need my character to jump so i cant just make the players y movement = 0.

Here's the code I've been using:

transform.position += Time.deltaTime * cameraMain.forward * Input.GetAxis("Vertical") * speedWilAim;

and I am trying to avoid separating the mouse look script into x and y pivots but if there is no alternative I will do that.


texts: Understanding the "gradient" in Perlin Noise

texts:
If I didn't get it wrong from the wikipedia, the word "gradient" should represents either the derivative for continuous functions, or the differential for discrete functions.
To rebuild the original function, I would integrate the gradient function, or calculate the partial sum of them.
Dot production between a unit vector and a gradient vector represents the slope/change-rate along the direciton of the unit vector.

But perlin noise seems unable to be explained. We calculate 4 gradient productions between related positions and random generated gradients in 4 corners, then simply interpolate them resulting the final value.

Is there something I've missed? How to understand operations on gradient vectors for perlin noise?


texts: How to parse HTTP response (JSONdata) in cocos2d-x

texts:
I am making a HTTP request to a server and I am getting data from the database. Now I want to parse the JSON data and get the data into variables like this:

std::vector<char> * buffer = response->getResponseData();
char * concatenated = (char *) malloc(buffer->size() + 1);
std::string s2(buffer->begin(), buffer->end());
strcpy(concatenated, s2.c_str());

Json * json = Json_create(concatenated);
std::string test1 = Json_getString(json, "id", "default");
std::string test2 = Json_getString(json, "pass", "default");

CCLog("HTTP Response : id : %s", test1);
CCLog("HTTP Response : pass : %s", test2);

But I am getting an error on:

Json *Json_getItem (Json *object, const char* string) {
Json *c = object->child;  //error on this line -- exc_bad_access
while (c && Json_strcasecmp(c->name, string))
c = c->next;
return c;
}

When I log...

 log("%s",concatenated);

...it outputs data like this:

 id:mtpass:thkr

Reference - https://gist.github.com/Tetz/81686772

So how to get the data in variables id and pass?


texts: How do I stop Unity's default FPS Controller from keeping momentum?

texts:
Unity's default FPS Controller keep momentum after you let go of the keys. Once you are up to full speed with WASD and let go, it continues to move for a bit.

How do I stop this momentum? Immediately upon letting go of the keys, I want the character to stop.

I am looking into the script already, but I am new to Unity. If someone can point me to what I am looking for, please do!

P.S. It appears it may be due to a connection to GetAxis which has built in momentum.
https://docs.unity3d.com/ScriptReference/Input.GetAxis.html


texts: How do I prevent other dynamic bodies from affecting the player's velocity with Box2D?

texts:
I'm working on my player object for my game.

PhysicsBodyDef def;
def.fixedRotation = true;
def.density = 1.0f;
def.position = Vec2(200.0f, 200.0f);
def.isDynamic = true;
def.size = Vec2(50.0f,200.0f);

m_player.init(def,&m_physicsEngine.getWorld());

This is how he moves:

b2Vec2 vel = getBody()->GetLinearVelocity();
float desiredVel = 0;

if (m_keys[ALLEGRO_KEY_A] || m_keys[ALLEGRO_KEY_LEFT])
{
    desiredVel = -5;
}
else if (m_keys[ALLEGRO_KEY_D] || m_keys[ALLEGRO_KEY_RIGHT])
{
    desiredVel = 5;
}
else
{
    desiredVel = 0;
}

float velChange = desiredVel - vel.x;
float impulse = getBody()->GetMass() * velChange; //disregard time factor
getBody()->ApplyLinearImpulse( b2Vec2(impulse,0), getBody()->GetWorldCenter(),true);

This creates a few problems. First, to move the player at a constant speed he must be given a high velocity. The problem with this is if he just comes in contact with a small box, he makes it move a lot.

Now, I can fix this by lowering his density, but then comes my main issue: I need other objects to be able to run into him, but when they do, he should be like a static wall and not move.

I'm not sure how to do that without high density. I cannot use collision groups since I still need him to be solid toward other dynamic things.

How can this be done? Essentially, how do I prevent other dynamic bodies from affecting the player's velocity?


texts: How to highlight non-rectangular hotspots?

texts:
So my question is highly related to Creating non-rectangular hotspots and detecting clicks.

Yet again, I've irregular hot-spots (think the game Risk). So basically, we can detect clicks on these hot-spots easily using color key mapping as discussed in above question which I don't have any problems implementing (which is also covered here in details).

The problem is about highlighting these irreguar hotspots. So let me explain the question a bit more - the above color key mapping guide uses this as a world map:

Then the author color-maps the imaginary countries:

Now we can now detect the country the pointer is over. In the same article author mentions outlining countries on mouse-over. Though to get the effect, he creates unique border assets for each country - like:

For the game I'm working on I'm using the same color-key mapping idea to detect hot-spots, but I didn't like the way of highlighting hot-spots. Coloring all the hot-spots is already a time-consuming job for me - as I have 25+ hot-spots for each map. Further, the need to have 25 unique border/highlight asset per hot-spot doesn't sound right.

Anyone have a better idea/suggestion on highlighting these hot-spots?


texts: 2D Grid-based Pathfinding with Elevation

texts:
I'm creating an isometric game which currently uses A* Pathfinding on a basic grid representation of the map.
Having elevations and allowing the Players to traverse up-and-down is an integral part of the game - however I'm stuck on exactly how to implement that, whether it be with A* or something else.
For example,
---------------------------------
| 0 | 0 | 0 | X | 0 | 4 | 4 | 4 |
---------------------------------
| 0 | 0 | 0 | 0 | 0 | 4 | 4 | 4 |
---------------------------------
| 0 | 0 | 1 | 2 | 3 | 4 | 4 | 4 |
---------------------------------

Assuming X is the Player, the numbers are tile elevations, and that the Player can only traverse tiles +/- 1 elevation to the tile they're currently on, is there an accepted/known way of doing this pathfinding?


texts: Is it better to combine or leave alone 2D polygons

texts:
I'm making a modular system for a 2D spaceship arcade like game, the user builds their own ship with equilateral triangles to make more complex shapes. When the ships are small it's no problem, but as you make bigger ships you would have to add more bodies to the physics engine, so I think I should just combine all the bodies and make a polygon outlining the shape I'm making and simply render it as multiple. But I've also heard it's really computationally expensive to use shapes other than squares, triangles, and circles.

Tldr: I have a compound of triangles, should I just leave it as is? Or make a polygon outlining the overall shape? Which is better performing? Is there anything I'm missing?


texts: Character Movement and Collision with Ragdoll Rigidbodies/Colliders?

texts:
I have a player character that I'm moving with a character controller script and it is moved by applying velocity to a Ridigbody.

This works when I have a rigidbody component on the player but my character also has ragdoll colliders and rigidbodies on each body parts (set up with Untiy's ragdoll wizard).

What I'd like to do is remove the ridigbody and collider that are on the player and use the ragdoll colliders and rigidbodies instead for physics movement and collision.

But it's not working! When I use the rigidbody from the skeleton Root and try to apply velocity the character won't move (animation plays but she keeps running on the same spot). What do I need to do to get this working?

Another issue is that if I leave the player rigidbody on but remove the large capsule collider I can move the character but collision doesn't work and she runs through static objects. I already tried with convex set to true on static meshes but it doesn't make a difference.

Does somebody know what causes movement and collision not to work with the ragdoll rigidbodies and colliders?


texts:
I am using Unreal Engine 4.25, and I have an issue with adding textures.
I have some textures right now in my landscape, but lately when I add a texture to the landscape, suddenly all texture disappear from my landscape - it looks like I did not add any textures at all.
How can I fix this issue?


texts: In unity when I am playing my game it displays fine, but when I build and run it to my nexus 5 there is this white something I don't even know over my game. Any suggestions for fixes?


texts: What technology(s)would be suitable for the front end part of a Java web game?

texts:
As asked in a previous question, I'm looking to create a small MMO that will be deployed onto GAE.

I'm confused about what technologies I could use for the user interface, I've considered the following

JSP Pages - I've got experience with JSP/JSTL and I would find this easy to work with, it would require the user having to "submit" the page each time they perform an action so may become a little clumsey for players.
Applet - I could create an applet that sits on the front end and communicates to the back end game engine, however I'm not sure how good this method would be and have not used applets since university..

What other options do I have? I don't have any experience in Flash/Flex so there would be a big learning curve there.

Are there any other Java based options I may be able to use?

My game will be text based, I may use some images, but I'm not intending to have any animations/graphics etc

Thanks


texts:
Based on Why is it so hard to develop a MMO?:

  Networked game development is not trivial; there are large obstacles to overcome in not only latency, but cheat prevention, state management and load balancing. If you're not experienced with writing a networked game, this is going to be a difficult learning exercise.

I know the theory about sockets, servers, clients, protocols, connections and such things.

Now I wonder how one can learn to write a network game:

How to balance load problems?
How to manage the game state?
How to keep things synchronized?
How to protect the communication and client from reverse engineering?
How to work around latency problems?
Which things should be computed local and which things on the server?
...

Are there any good books, tutorials, sites, interesting articles or other questions regarding this?

I'm looking for broad answers, but specific ones are fine too to learn the difference.


texts:
I have imported image effects from asset store in my project.
When imported, I've got 5 error messages :

Assets/Standard Assets/Effects/TonemappingColorGrading/Editor/TonemappingColorGradingEditor.cs(370,134): warning CS0618: `UnityEditor.TextureImporterFormat.AutomaticTruecolor' is obsolete: `Use textureCompression property instead'

What to do ?


texts: Smooth Camera Rotation around 90 degrees

texts:
I'm developing a third person 3D platformer in XNA. My problem is when I try to rotate the camera around the player.
I would like to rotate (and animate) the camera 90 degrees around the player. So the camera should rotate until it has reached 90 degrees from the starting position.
I cannot figure out how to keep track of the rotation, and when the rotation has made the full 90 degrees.

Currently my cameras update:

public void Update(Vector3 playerPosition) {
    if (rotateCamera) {
        position = Vector3.Transform(position - playerPosition, Matrix.CreateRotationY(0.1f)) + playerPosition;
    }
    this.viewMatrix = Matrix.CreateLookAt(position, playerPosition, Vector3.Up);
}

The initial position of the camera is set in the constructor.
The "rotateCamera" bool is set on keypress.

Thanks for the help in advance.

Cheers.


texts: Midpoint displacement generating unsatisfactory terrain

texts:
Following this lesson for implementing mid-point displacement algorithm for terrain generation. I aim at generating a wavefront(obj) file of the terrain

I have an array of dimension (2^n + 1) x (2^n + 1).
The corners of the 2d array is initialized with random numbers.

n = plug_in_n
arr = Array.new(2**n + 1) { Array.new(2**n +1) { 0 } }
n_augmented = 2**n

arr[0][0] = rand(10 + 1)
arr[0][n_augmented] = rand(10 + 1)
arr[n_augmented][0] = rand(10 + 1)
arr[n_augmented][n_augmented] = rand(10 + 1)

This is the script I have written for generating a terrain.

a = arr
n_augmented_copy = n_augmented
while n_augmented > 1

puts "n_augmented = " + n_augmented.to_s
i = 0
while(i < n_augmented_copy)
    j = 0
    while(j < n_augmented_copy)
        a[i][j+(n_augmented)/2] = (a[i][j] + a[i][j+n_augmented]) / 2.0  + (rand 0.0..1.0)
        a[i + (n_augmented) / 2][j + n_augmented] = (a[i][j + n_augmented] + a[i + n_augmented][j + n_augmented]) / 2.0 + (rand 0.0..1.0)
        a[i + n_augmented][j +( n_augmented) / 2] = (a[i + n_augmented][j] + a[i + n_augmented][j + n_augmented] )/ 2.0 + (rand 0.0..1.0)
        a[i + (n_augmented) / 2][j]  = (a[i + n_augmented][j] + a[i][j] )/ 2.0 + (rand 0.0..1.0)
        a[i + (n_augmented) / 2][j +( n_augmented) / 2] = ((a[i][j+(n_augmented)/2] + a[i + (n_augmented) / 2][j + n_augmented] + a[i + n_augmented][j +( n_augmented) / 2]  + a[i + (n_augmented) / 2][j]))/ 4.0  + (rand 0.0..1.0)
        j = j + n_augmented
    end
    i = i + n_augmented
end
# binding.pry
# p_arr(a)
n_augmented = n_augmented / 2

end

Demonstrating a case for n = 2: I have omitted the random-displacement rand 0.0..1.0to check if the heightmap chucks are getting calculated fine.

Here is how the iterations look like

n_augmented = 4
    9     0   5.5     0     2
    0     0     0     0     0
  6.5     0   5.5     0   4.5
    0     0     0     0     0
    4     0   5.5     0     7
n_augmented = 2
    9  7.25   5.5  3.75     2
 7.75 6.625   5.5 4.375  3.25
  6.5   6.0   5.5   5.0   4.5
 5.25 5.375   5.5 5.625  5.75
    4  4.75   5.5  6.25     7

If I form a mesh using this alone, it results in a plane like:

Considering the random displacement for this case, it results in :

For n = 5, It looks like :

This is not desirable since I cannot see any peaks and slopes.

Here is the ruby script  : CODE


texts:
Now my Image isn't loading to the screen. I tried to be decorative with the code but since it isn't working I made it just like the video I'm whatching.
I don't get any exceptions, but the image doesn't appear still.

My main desktop launcher class:

public class DesktopLauncher {
public static void main (String[] arg) {
    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
    config.title = " Game Tests ";
    config.width = 500;
    config.height = 400;
    config.useGL30 = true;

    new LwjglApplication(new MyGdxGame(), config);
}
}

My Game class:

public class MyGdxGame extends Game {

@SuppressWarnings("unused")
private TestScreenA GameScreen;

@Override
public void create () {
    //loads image
    AssetLoaderTest.load();
    GameScreen = new TestScreenA(this);

}

@Override
public void render () {

}
}

My Screen class:

public class TestScreenA implements Screen{

@SuppressWarnings("unused")
private MyGdxGame game;

//Camera
private OrthographicCamera camera;

//images etc.
private SpriteBatch batch;

public TestScreenA(MyGdxGame game) {
    this.game = game;

    //Camera
    camera = new OrthographicCamera();
    camera.setToOrtho(false, 1920, 1080);

    batch = new SpriteBatch();

}

public void render(float delta) {
    //clears the screen with white
    Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

    //loads images scaled to camera
    batch.setProjectionMatrix(camera.combined);

    batch.begin();
        batch.draw(AssetLoaderTest.s, 0, 0);
    batch.end();

}

public void resize(int width, int height) {

}

public void show() {

}

public void hide() {

}

public void pause() {

}

public void resume() {

}

public void dispose() {

}

}

My AssetLoaderTest class:

public class AssetLoaderTest {

//Images etc.

public static Texture t;
public static Sprite s;

static void load() {

    t = new Texture(Gdx.files.internal("testImgs/badlogic.jpg"));
    //Automatically scales texture based off of window size
    t.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    //a sprite is pretty much the body and the texture is the texture or image of it
    s = new Sprite(t);
    s.flip(false, true);

}

}


texts:
Inside the script code of the the hero(object) I want add the possibility to change its sprite.

So the player hits the space button and the sprite changes into the other sprite already added to the project.

Can you provide me a sample code to do this?


texts: How can I fix problems caused by "ForceMode2D.Force"?

texts:
I'm making a 2D platformer with Unity. I used transform.position for movement but it caused some problems like vibration, so I decided to use AddForce.ForceMode2D.Force instead. Since this uses mass for moving the player, it makes the player either so heavy and hard to control (even when the mass is 1) or so quick and fast.  I tried changing the mass and speed but I haven't found the setting that makes a smooth movement. Also, the jumping has a problem. The player will be suspended in the air for a few seconds after the jumping. I'm just looking for a way  to make AddForcesmoother and solve these problems.
Here's my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerController : MonoBehaviour
{
    [SerializeField] private float jumpSpeed;

    public float maxSpeed = 5f;
    public float maxAcceleration = 50f;
    public float maxDeceleration = 100f;

    [SerializeField] private LayerMask ground;
    private PlayerActionControls playerActionControls;
    private Rigidbody2D rb;
    private PolygonCollider2D pol;
    private Animator animator;
    private Vector2 movementInput;

    private void Awake()
    {
        playerActionControls = new PlayerActionControls();
        rb = GetComponent<Rigidbody2D>();
        pol = GetComponent<PolygonCollider2D>();
        animator = GetComponent<Animator>();
    }

    private void OnEnable()
    {

        playerActionControls.Enable();

    }

    private void OnDisable()
    {

        playerActionControls.Disable();
    }

    void Start()
    {
        playerActionControls.Land.Jump.performed += ctx => Jump(ctx.ReadValue<float>());

    }

    private void Jump(float val)
    {
        if (val == 1 && IsGrounded())
        {
            rb.AddForce(new Vector2(0, jumpSpeed), ForceMode2D.Impulse);

        }
    }
    private bool IsGrounded()
    {

        Vector2 topLeftPoint = transform.position;
        topLeftPoint.x -= pol.bounds.extents.x;
        topLeftPoint.y += pol.bounds.extents.y;

        Vector2 bottomRightPoint = transform.position;
        bottomRightPoint.x += pol.bounds.extents.x;
        bottomRightPoint.y -= pol.bounds.extents.y;

        return Physics2D.OverlapArea(topLeftPoint, bottomRightPoint, ground);
    }
    void FixedUpdate()
    {

     Vector2 movementInput = playerActionControls.Land.Move.ReadValue<Vector2>();

     movementInput = Vector2.ClampMagnitude(movementInput, 1f);
     Vector2 desiredVelocity = movementInput * maxSpeed;
     AccelerateTo(desiredVelocity);

    var scale = transform.localScale;
    if(scale.x * rb.velocity.x < 0) {
        scale.x *= -1;
        transform.localScale = scale;
    }

    void AccelerateTo(Vector2 DesiredVelocity) {

    var deltaV = desiredVelocity - rb.velocity;
    var acceleration = deltaV / Time.deltaTime;

    float limit = maxAcceleration;
    if (Vector3.Dot(rb.velocity, desiredVelocity) <= 0f)
        limit = maxDeceleration;
    acceleration = Vector2.ClampMagnitude(acceleration, limit);

    Vector2 force = rb.mass * acceleration;
    rb.AddForce(force);
   }
 }
}


texts: How to handle simultaneous mouse and keyboard input with sdl?

texts:
I'm making a game in SDL2 that so far is basically just a top down shooter, where the player aims at the mouse. When I run the game, you can move properly and shoot properly, and shoot and move the mouse at the same time properly, but you cannot shoot while moving. For example, if I'm using the gatling gun which is fully automatic (as long as I hold the mouse down it keeps on shooting), and I start shooting, then press the w key to move, it stops shooting right away, and doesn't start again until I click again. Here is my code:

void Main::handleInput2(void)
{
double xcomponent,ycomponent,xVel,yVel,angle;
SDL_GetMouseState(&mouseX,&mouseY);
xcomponent = mouseX - (player.getBarrelX() + xOffset);
ycomponent = mouseY - (player.getBarrelY() + yOffset);
angle = atan2(ycomponent,xcomponent);
xVel = cos(angle);
yVel = sin(angle);

if(screen->getEvent()->type == SDL_KEYDOWN)
{
    if(screen->getEvent()->key.keysym.sym == SDLK_a)
    {
        player.setVelX(-1 * player.getSpeed());
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_d)
    {
        player.setVelX(player.getSpeed());
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_w)
    {
        player.setVelY(-1 * player.getSpeed());
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_s)
    {
        player.setVelY(player.getSpeed());
    }
}
if(screen->getEvent()->type == SDL_KEYUP){
    //if(screen->getEvent()->key.keysym.sym = SDLK_8) player.setVelocity(-2,-2); TEST PASSED
    if(screen->getEvent()->key.keysym.sym == SDLK_a)
    {
        player.setVelX(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_d)
    {
        player.setVelX(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_w)
    {
        player.setVelY(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_s)
    {
        player.setVelY(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_1) //Paintball Gun
    {
        player.setWeapon(0);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_0) //Glock
    {
        player.setWeapon(1);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_2) //Skorpion
    {
        player.setWeapon(2);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_3) //Ballistic Knife
    {
        player.setWeapon(5);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_4) //Spas 12
    {
        player.setWeapon(4);
    }
    if(screen->getEvent()->key.keysym.sym == SDLK_5)
    {
        player.setWeapon(3);
    }
}
if(screen->getEvent()->type == SDL_MOUSEBUTTONDOWN || screen->getEvent()->type == SDL_MOUSEMOTION&SDL_MOUSEBUTTONDOWN)
{
    if(screen->getEvent()->button.button == 1)
    {
        player.Shoot(1,xVel,yVel,screen);
    }
    if(screen->getEvent()->button.button == 3)
    {
        player.Shoot(3,xVel,yVel,screen);
    }
}
}

This was originally all in switch statements, but I thought it might work in if statements. I also tried handling SDL_KEYDOWN and SDL_MOUSEDOWN the same way as I did with SDL_MOUSEDOWN and SDL_MOUSEMOTION. I tried stuff like

if(screen->getEvent()->type == SDL_KEYDOWN|SDL_MOUSEDOWN)
{
    ...
}

if(screen->getEvent()->type == SDL_MOUSEDOWN|SDL_KEYDOWN)
{
    ...
}

if(screen->getEvent()->type == SDL_MOUSEDOWN&SDL_KEYDOWN)
{
    ...
}

if(screen->getEvent()->type == SDL_KEYDOWN&SDL_MOUSEDOWN)
{
    ...
}

But none of those helped, each one in fact made it worse.
Seeing as that SDL is meant for making games, I would imagine there must be a way around this.
Does anyone know how?


texts:
I am working on a platformer 2D, and i am currently focusing on collision. I have the actual rectangle(class: Rect) and i can detect if the player-model is intersepting it. However, when it comes from the side, that is when the problems appear: i can prevent it from going down after the interseption but i cant prevent it if it intersepts with the edges. how can I  make a better collision system?

EDIT:

I have worked a little on a system, but it doesnt work. Help me improve this:

for(Platform p : game.platforms){
            if(Rect.intersects(getBounds(), p.getBounds())){
                coll = true;
                int px = p.x;
                int py = p.y;
                if((x + 100) >= px  && (x + 100) <= px + 10){
                    x = px - 101;
                    y += 100;
                    Toast.makeText(game.c, "if(x + 100) >= px  && (x + 100) <= px + 10)", Toast.LENGTH_LONG).show();
                } else if(y  <= (py + 1) && y  >= py + p.height + 10){
                    y = 0;
                    Toast.makeText(game.c, "if8y <= (py + 1) && y  >= py + p.height + 10)", Toast.LENGTH_LONG).show();
                } else if(y  >= py ){
                    y = py - 100;
                    Toast.makeText(game.c, "if(y >= py", Toast.LENGTH_LONG).show();
                }
            }
        }
        if(!coll){
            y += 6;

        }else{

            heightJumped = 0;
            canJump = true;
            isInAir = false;
            jumping = false;
        }
        coll = false;
    }


texts: Why swapping buffers takes different amounts of time?

texts:
When my program starts, almost nothing is on screen, just couple of lights and spheres. My FPS is at ~50. The Speed measurements looks like this:

UpdateFrame took 0 ms
Clearing lights queue: 0 ms
Queue floor for rendering: 0 ms
Clearing and starting deferred: 0 ms
base.OnRenderFrame: 0 ms
ModelRenderer.Render (): 0 ms
LightingEngine.RenderFrame (): 0 ms
deferred.RenderOnScreen (): 0 ms
Gui.Render (): 1 ms
SwapBuffers (): 18 ms
ModelRenderer.Clear (): 0 ms

Whole rendering took: 19 ms

But then after a while the program has been running for some time and more lights and spheres are added, the FPS is ~40 and the speed measurements are as follows:

UpdateFrame took 0 ms
Clearing lights queue: 0 ms
Queue floor for rendering: 0 ms
Clearing and starting deferred: 0 ms
base.OnRenderFrame: 5 ms
ModelRenderer.Render (): 4 ms
LightingEngine.RenderFrame (): 7 ms
deferred.RenderOnScreen (): 0 ms
Gui.Render (): 0 ms
SwapBuffers (): 7 ms
ModelRenderer.Clear (): 0 ms

Whole rendering took: 23 ms

I had VSYNC off for this test. This clearly implies that my GPU has too much to chew. I want to know why the SwapBuffers() is taking less time with more stuff on screen, shouldn't it take more or equal time then?


texts: How to manage VBO geometry for constantly changing data?

texts:
Before going into specifics, I'm mostly interested in making simple 2D games with some 3D elements, not fancy AAA.

Based on what I've gathered, everyone seems to suggest to use OpenGL 3+ with shaders, instead of the 2.x style of glVertex/glBegin/glEnd. Now I do understand the reasoning behind moving to VBO and shaders, as it gives greater control and performance.

But it seems that it also forces me to produce all of the geometry beforehand, buffer is it somehow, generate the VBO, and then send all that to a single vertex/fragment shader to render it, correct?

It also seems that I need to have a single shader process completely different types of vertices, which means there has to be a lot of redundant information in the VBO? Or is there a way to have multiple VBOs? I know it is possible to have multiple shaders and swap them, but I haven't figured out when one would need that, considering I only have a single active VBO?

Now comes the real question.

Consider I'm making something like a procedurally generated growing plant, where each frame changes the whole geometry slightly (or just adds something). For simplicity, let's just say the plant is a bunch of colored ellipses. How do I structure the algorithm for "drawing" the plant? Would I just build the whole VBO from scratch, given that the vertex data changes all the time?

Also considering that the number of plants and their size can vary greatly, how do I avoid re-allocate memory for the VBO on each frame? Do I just use a large enough buffer, which would be able to store the maximum amount of geometry I can manage in my shaders (like a 512MB static array)?


texts: Libgdx Admob how to hide ad on specific screen?

texts:
I've recently started learning Java for android development.
My first game is almost ready to publish in Google Play, but I'm affraid that google might say that on the one screen, the ad may be clicked accidentally, So I would like to hide it on that screen.
The thing is, that Adview is initiated only in AndroidLuncher class in android project, but all the other classes are in core project. So what I'm asking for is a way to instruct Admob to hide when player enters GameScreen. Is that possible?

I could provide some code, but I don't know which part could help you, so I'll just post the AndroidLauncher Class onCreate method:

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    config.useAccelerometer = false;
    config.useCompass = false;

    RelativeLayout layout = new RelativeLayout(this);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    // Create the libgdx View
    View gameView = initializeForView(new MainClass(), config);

    AdView AdView = new AdView(this);
    AdView.setAdSize(AdSize.SMART_BANNER);
    AdView.setAdUnitId("ca-app-pub-SECRETCODE/HERE"); //The AdUnitId
    if(isNetworkAvailable())
    {
        AdView.setBackgroundColor(Color.BLACK);
    }
    AdRequest.Builder adRequest = new AdRequest.Builder();
    adRequest.addTestDevice("HERE_TOO"); //Test device
    AdView.loadAd(adRequest.build());

    layout.addView(gameView);

    // Add the AdMob view
    RelativeLayout.LayoutParams adParams =
            new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
    adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

    layout.addView(AdView, adParams);

    // Hook it all up
    setContentView(layout);

    AdView.setVisibility(View.VISIBLE);
}

This code works just fine, so I would prefer not to change it, as I've spent many hours getting it to work :)


texts: Unreal Engine 4 HierarchicalInstancedStaticMesh (HISM) not distance culling

texts:
What I'm trying to do:
I am trying to programmatically spawn a lot of HierarchicalInstancedStaticMesh on a very very large ProceduralMeshComponent (PMC) (very simplified for the sake of this question).
I generate the "ground" PMC in chunks during run time, and then spawn instances at points on the mesh.

An initial n amount of these  are generated before the player spawns. Additional chunks spawn by calculating values with a separate thread and then spawning them from the original thread. All I am doing in the separate thread is calculating vectors essentially

I have an actor with just a HISM component at the root.

Cull start and end distance is set to 5000
Mesh material has Dithered LOD Transition set to true

What is happening:
The culling on the HISM is simply not working.

Sometimes It won't even show up to begin with
When it does show up, it doesn't cull no matter how far away the camera gets (spectator)
Sometimes it will cull correctly on the initially spawned chunks, but not on the chunks that were generated and spawned after the player spawned

The weirdest part, is that I am also spawning an HISM of a different mesh in exactly the same manner, and it is culling perfectly (though admittedly there are far FAR fewer instances)
Example code:
Here is an example of what I am trying to do. The Terrain actor is placed in the world, the HISM is referenced in a public variable, and this code runs in BeginPlay (and Tick, for subsequent chunks)
Terrain.H:
// The Actor with the HISM as the root component
UPROPERTY(Category = "hism", BlueprintReadWrite, EditAnywhere) TSubclassOf<AActor> FoliageInstance;

Terrain.cpp:
auto spawner = World->SpawnActor<AActor>(FoliageInstance, FVector(0, 0, 0), FRotator::ZeroRotator);

// Another class I wrote that just calculates a ton of vectors
TArray<FVector> spawnPoints = OtherClass.GetATonOfRandomVectors();

// Add an instance for each of the spawn points
for (auto& spawn: spawnPoints)
{
    FRotator grassRotation = FRotator(rand() % 5, rand() % 360, rand() % 5);
    FTransform grassTransform = FTransform(grassRotation, spawn);

    if (spawner != nullptr)
    {
        auto instance = Cast<UHierarchicalInstancedStaticMeshComponent>(spawner->GetRootComponent());
        instance ->AddInstance(grassTransform);
    }
}


texts: Categorize contact & overlap cases for 2D & 3D axis-aligned bounding boxes

texts:
My question is similar to this one. I want to determine whether two axis-aligned boxes are not only intersecting, but if they are intersecting and just touching on one edge or face, or if they are overlapping in some way.

Below is an example of these two options.


texts: Editor-Assignable function pointer in UE4 C++?

texts:
So I have a TriggerBox that I'm using as a pressure pad, and I want to be able to attach objects to it that, when the TriggerBox is activated, will have specific functions called. Similar to unity's UI buttons, where you can assign a function to be called when the button is clicked.

I am working as the sole programmer, and the rest of my team are designers. They need to be able to assign the object's function to the TriggerBox from within the editor.

I have attempted to use C++'s function pointers, but I have not been able to find a way to make them assignable in the editor.

Is there a solution to this? If not, any suggestions on better ways to do this?


texts: Am I allowed to sell a XNA game by myself?

texts:
I've just started the development of an XNA game, and I'm asking myself if it wouldn't be better to use an open-source alternative since I absolutely want to keep the complete control over my game. I need to be able to sell it to whoever I want, using the media I want.

Based on the XNA license and all that sort of legal stuff, am I allowed to sell an XNA game on my own, or am I forced to sell it through the Xbox Live Marketplace?

I'd like to see some reliable reference with your answer.


texts: Why are my texture coordinates always (0,0) in this shader?

texts:
What I'm trying to do is add my depth buffers values to my scene, ie. I'm trying to make objects closer to the camera darker and objects further away lighter. Which should be easy: just render the depth buffer to a texture, and then render the scene, multiplying each pixels colour by the colour value at the same coordinates in my depth-buffer texture...

Yet I don't know how to use coordinates for textures.

Or more like it's just failing. What's happening is that the vertex shader is only using the (0,0) coordinate of my texture, so the entire scene changes colour depending on what's there.

What I'm doing is this (the critical stuff from my render function):

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, depthTextureId);   //Binds the texture
box.render();    //Sets the viewing matrix and renders a test VBO

I guess that's the right way to bind a texture? Anyhoo, here's the vertex shader's important stuff:

out vec4 ShadowCoord;

void main() {
    gl_Position = PMatrix * (VMatrix * MMatrix) * gl_Vertex;  //Projection view and model matrices
    ShadowCoord = gl_MultiTexCoord0;    //something I kept seeing in examples, was hoping it would work.
}

It seems gl_MultiTexCoord0 is the problem? Maybe?

The frag shader sets the colour using this function:

vec4(texture2D(ShadowMap, ShadowCoord.st).x * vec3(Color), 1.0);

Where the ShadowMap is the sampler2D for the texture, and Color is the vertex's color...

So what am I missing? How come the coordinates are not changing from 0,0?


texts:
I'm creating a top-down 2D space game in LIBGDX for android.

When spaceship is going forward it will look like this:

when it goes upward I want to change it's direction with a nice animation so it seems like a real spaceship. A between frame would be like this:

I have rendered the spaceship in different Z axis degrees from ship0 to ship90. Calculating rotation on XY plane wouldn't be so hard, but I don't know how to calculate the rotation on Z axis so I can choose the right sprite to use.