texts:
Preface: I am terrible at using quaternions right.

I wanted to create a world rotation independent mouselook script. That is, no matter the 'down' for the camera, the mouselook should feel natural to the player in relation to what is displayed on screen.

I now have the following script running on update in my camera:

        Quaternion worldRot = Quaternion.LookRotation(Vector3.forward, Vector3.left);

    xRot += -rotSpeed * Input.GetAxis("Mouse Y");
    yRot += rotSpeed * Input.GetAxis("Mouse X");
    transform.rotation =
        Quaternion.AngleAxis(yRot, worldRot * Vector3.up) *
        Quaternion.AngleAxis(xRot, worldRot * Vector3.right) *
        worldRot;

Unsurprisingly, it tumbles all over the place. I think the issue is in basing the rotation angles on the worldRot (World rotation as seen by the camera), while then also rotating the whole by worldRot. I cannot get my head around how else to go about it, though...

My initial alternative was to use

        transform.rotation =
        Quaternion.AngleAxis(yRot, Vector3.up) *
        Quaternion.AngleAxis(xRot, Vector3.right) *
        worldRot;

But this anchors the mouse's movements to the world rather than the camera, which as described above isn't desired either.

Based on this (or, perhaps, in a completely different way), how do I make a mouselook system with an arbitrary down vector?


texts: Is it possible to apply a texture inside a GL_LINE_LOOP?

texts:
I am creating a game using Box2D and OpenGL ES 1.1.

I am taking the b2PolygonShape vertices and converting them into an OpenGL ES 1.1 GL_LINE_LOOP. The debugging view looks great, but now I want to apply textures to the inside of the line loop.

Is this possible? I used line loop instead of triangles because I am not sure how to handle complex polygons using triangles.


texts:
q1. After passing stencil test, depth test, etc. what version of "depth" of fragments after primitive rasterisation will be written to depth buffer? With shifted values or without?
(Due to documentaion as I see it will be shifted version)

q2. Code in fragment shader will receive shifted version of gl_FragCoord.z, isn't it?


texts: How can I use Blender-style UVs (and not per-vertex) in OpenGL?

texts:
In Blender, UVs are stored "per face vertex", meaning that if you have a plane made of 2 triangles, you will have 2 faces, 4 vertices but 6 UV coordinates.

I made a basic export script, and exported UVs with help from the Blender Stack Exchange, since I do not know much about Blender UV format:

for p in mesh.polygons:
    for vert, loop in zip(p.vertices, p.loop_indices):
        for z in (mesh.uv_layers.active.data[loop].uv
            if mesh.uv_layers.active is not None else (0.0, 0.0)):  # uv
            f.write(struct.pack('f', z))

The UVs are stored as a std::vector of vec2s, in the engine, and uploaded to OpenGL like so:

glBufferData(GL_ARRAY_BUFFER, mdl.uvs.size()
    * sizeof(mdl.uv[0]), &mdl.uvs[0], GL_STATIC_DRAW);

How can I use the correct Blender UV format, without wasting memory, or turn the per face vertex UVs into per vertex UVs?


texts: Weird issue in collision resolution of non-static bodies

texts:
I'm a bit of a beginner in engine development, so I decided to write my own engine from scratch so I could learn more about what happens under everything.

I've been progressing fairly well, except the physics engine side of things have been giving me a bit of a headache.

Here's a gif of what I mean:

Essentially, the engine works just fine as long as the player is not colliding with another non-static body from either above, or from right to left.

Here's my collision resolution code written in go:

package resources

import (
  "game/pidgeot-socket/ecs"

  "github.com/bxcodec/saint"
)

type PhysicsSystem struct {
  Hub *Hub
}

func (system PhysicsSystem) Loop() {
  entities, err := system.Hub.World.AllEntitiesWithComponent(ecs.CollisionComponent)
  if err != nil { return }

  for e, _ := range entities {
    // apply impulse
    c_p, _ := system.Hub.World.GetComponent(e, ecs.CollisionComponent)
    c := (*c_p).(*ecs.Collision)

    p_p, _ := system.Hub.World.GetComponent(e, ecs.PositionComponent)
    p := (*p_p).(*ecs.Position)

    if c.WithGravity {
      // Add gravity
      c.ImpulseY = saint.Min(c.ImpulseY + 1, c.MaxSpeedY)
    }

    // apply impulse
    p.NextY = p.Y + c.ImpulseY
    p.NextX = p.X + c.ImpulseX
  }

  // resolving collisions
  for e1, _ := range entities {
    c1_p, _ := system.Hub.World.GetComponent(e1, ecs.CollisionComponent)
    c1 := (*c1_p).(*ecs.Collision)

    if c1.IsStatic { continue }

    for e2, _ := range entities {
      if e1 == e2 { continue }

      system.ResolveCollision(entities, e1, e2)
    }
  }

  // moving entities
  for e, _ := range entities {
    p_p, _ := system.Hub.World.GetComponent(e, ecs.PositionComponent)
    p := (*p_p).(*ecs.Position)

    if (p.X != p.NextX || p.Y != p.NextY) {
      p.X = p.NextX
      p.Y = p.NextY

      system.Hub.broadcast <- system.Hub.World.GetComponentMessage(e, p_p)
    }
  }
}

func (system PhysicsSystem) ResolveCollision(entities map[ecs.EID]*ecs.Component, e1 ecs.EID, e2 ecs.EID) {
  c1_p, _ := system.Hub.World.GetComponent(e1, ecs.CollisionComponent)
  p1_p, _ := system.Hub.World.GetComponent(e1, ecs.PositionComponent)
  c1 := (*c1_p).(*ecs.Collision)
  p1 := (*p1_p).(*ecs.Position)

  c2_p, _ := system.Hub.World.GetComponent(e2, ecs.CollisionComponent)
  p2_p, _ := system.Hub.World.GetComponent(e2, ecs.PositionComponent)
  c2 := (*c2_p).(*ecs.Collision)
  p2 := (*p2_p).(*ecs.Position)

  // resolve y-axis
  collidingX := IsOverlapping(p1.X, p1.X + c1.W, p2.X, p2.X + c2.W)
  collidingY := IsOverlapping(p1.NextY, p1.NextY + c1.H, p2.NextY, p2.NextY + c2.H)
  colliding := collidingX && collidingY

  if colliding {
    direction := func (impulse int) int {if impulse < 0 { return 1 } else { return -1 }}(c1.ImpulseY)
    overlap := CalculateOverlap(p1.NextY, p1.NextY + c1.H, p2.NextY, p2.NextY + c2.H)

    p1.NextY += (direction * overlap)
    c1.ImpulseY = 0
    c1.IsJumping = false
  }

  // resolve x-axis
  collidingX = IsOverlapping(p1.NextX, p1.NextX + c1.W, p2.NextX, p2.NextX + c2.W)
  collidingY = IsOverlapping(p1.Y, p1.Y + c1.H, p2.Y, p2.Y + c2.H)
  colliding = collidingX && collidingY

  if colliding {
    direction := func (impulse int) int {if impulse < 0 { return 1 } else { return -1 }}(c1.ImpulseX)
    overlap := CalculateOverlap(p1.NextX, p1.NextX + c1.W, p2.NextX, p2.NextX + c2.W)

    p1.NextX += (direction * overlap)
  }

  for e3, _ := range entities {
    if e1 == e3 { continue }

    c3_p, _ := system.Hub.World.GetComponent(e3, ecs.CollisionComponent)
    p3_p, _ := system.Hub.World.GetComponent(e3, ecs.PositionComponent)
    c3 := (*c3_p).(*ecs.Collision)
    p3 := (*p3_p).(*ecs.Position)

    collidingX = IsOverlapping(p1.NextX, p1.NextX + c1.W, p3.NextX, p3.NextX + c3.W)
    collidingY = IsOverlapping(p1.NextY, p1.NextY + c1.H, p3.NextY, p3.NextY + c3.H)
    colliding = collidingX && collidingY

    if colliding { system.ResolveCollision(entities, e1, e3) }
  }
}

Anything I could do to solve that issue?


texts: Game was resized incorrectly for no apparent reason (GameMaker)

texts:
I exported the game with the following graphics settings:

OBS - Interpolate colors between pixels would be like a Antiliasing. I do not think it is the cause of the problem, but I will test without and come back with an edit if it is.

I tested the game on a PC with the following settings: Intel Core 2 Duo CPU e8200 @ 2,66GHz 2,66GHz / 4GB RAM / monitor e943Fwsk 18,5'

Checking Keep aspect ratio this should not happen:

Talking with the owner of LAN house we discussed that could be because the monitor is very large and the fact that the PC does not have a video card and it is components do not support the size of the monitor. But he did not give me certainly.

Curiosly (or not) this was the only computer that had no version on DirectX. The DirectX was installed together with the game by the game installer itself. If I am not mistaken in version 9, most computers have least version 11.


texts: How to apply a shader to only one side of an object in Unity3D

texts:
So I have this rather simple surface shader that essentially cuts a hole in the object based on another texture.

Shader "Custom/NewSurfaceShader" {
    Properties {
        _MainTex("Texture (RGB)", 2D) = "white" {}
    _SliceGuide("Slice Guide (RGB)", 2D) = "white" {}
    _SliceAmount("Slice Amount", Range(0.0, 1.0)) = 0.5
    }
    SubShader {
        Tags { "RenderType"="Opaque" }
        Cull OFF
        CGPROGRAM

#pragma surface surf Lambert addshadow
        struct Input {
        float2 uv_MainTex;
        float2 uv_SliceGuide;
        float _SliceAmount;
    };
    sampler2D _MainTex;
    sampler2D _SliceGuide;
    float _SliceAmount;

    void surf(Input IN, inout SurfaceOutput o) {

        clip(tex2D(_SliceGuide, IN.uv_SliceGuide).rgb - _SliceAmount);
        o.Albedo = tex2D(_MainTex, IN.uv_MainTex).rgb;
    }
    ENDCG
    }
        Fallback "Diffuse"
}

This produces the following effect.

Now as cool as this looks I want to only apply it to, let's say, one side of the cube and its opposite side. Any suggestions on how do I go about doing this will be appreciated.


texts: split/divide/extract/separate mesh indices&vertex in n

texts:
I'm totally lost. I'm trying to split/divide/extract/separate a mesh into sub-meshes via bbox test. But I just realized that I need to properly split indices and vertex and I have no idea how o.o... here is the splitting code that "fails" because my indices/vertex needs a proper re-arranging that I have no idea how to solve o.o.

for (auto &box:aabb) { //// list of bboxes
    for (int indi = 0; indi < mIndices.size(); indi += 3) { /// get 3 indices for 1 triangle
        offX = mIndices[indi];
        offY = mIndices[indi + 1];
        offZ = mIndices[indi + 2];
        /// Check if any of the vertex is inside the box
        if (box.contains(mVertex[offX]) || box.contains(mVertex[offY]) || box.contains(mVertex[offZ]))
           {
            /// bellow code is wrong, I'm over-adding vertex even if they
            /// exist, and I'm adding wrong indices because new mVertex/indices arrays are of
            /// different sizes to source one... oh dear... I need to add an only missing vertex,
            /// and indices re-mapped to proper existing/new vertexes.

            box.mVertex.push_back(mVertex[offX]);
            box.mVertex.push_back(mVertex[offY]);
            box.mVertex.push_back(mVertex[offZ]);
            box.mIndices.push_back(offX);
            box.mIndices.push_back(offY);
            box.mIndices.push_back(offZ);
        };
    }
}

If any1 could help with this, this would be amazing. I'm not worried if 1 triangle is being duplicated across 2 bounding boxes or even more. As the aaBB can have random positions. I just need each aabb with its own vertex/indices set that can create mesh.

EDIT1.

The only way I could think of doing it is this > it feels quite..."bad tho...

void aabb::addTriangle(QVector3D &x, QVector3D &y, QVector3D &z) {
if (mVertex.contains(x)) {
    mIndices.push_back(mVertex.indexOf(x));
} else {
    mVertex.push_back(x);
    mIndices.push_back(mVertex.size() - 1);
}
if (mVertex.contains(y)) {
    mIndices.push_back(mVertex.indexOf(y));
} else {
    mVertex.push_back(y);
    mIndices.push_back(mVertex.size() - 1);
}
if (mVertex.contains(z)) {
    mIndices.push_back(mVertex.indexOf(z));
} else {
    mVertex.push_back(z);
    mIndices.push_back(mVertex.size() - 1);
}

}

EDIT 2.
Thanks to ErnieDingo I'm now not copying vertex in to each aabb object, but only adding triangles(3indices) that if either is being contained by bbox. Then I pass pointer to base mesh vertexArray for further tests down the line


texts:
I'm new to the Entity Component System pattern and there's something I cannot figure out. Let's say I have the following entity:

Player: {
    Components: [
        Position: {
            x: 0,
            y: 0
        },
        Health: {
            max: 100,
            current: 50
        },
        Sprites: { ... }
    }
}

When I render an entity that has a Health component I also would like to render a health bar above that entity. Do I treat the health bar as a new entity and attach it to the Player i.e., the Player becomes a composite of entities; or it [the Health bar] should be part of the Health component, in which case how would it be rendered / created?

To illustrate what I'm trying to say:

Player: {
    ChildEntities: [
        Character: {
            Components: [
                Position: { x:parent.x, y:parent.y },
                Sprites: { parent... }
            ]
        },
        HealthBar: {
            Components: [
                Position: { x:parent.x, y:parent.y },
                Health: { max:parent.max, current:parent.current }
            ]
        }
    ],
    Components: [
        Position: {
            x: 0,
            y: 0
        },
        Health: {
            max: 100,
            current: 50
        }
    }
}

Is there an idiomatic / preferred way of doing this? Thanks.


texts: Performance/architectural implications of calling SpriteBatch.Begin/End in many different places?

texts:
I notice some code samples only call SpriteBatch.Begin and SpriteBatch.End in the game's main draw method and then draw everything within that method through direct SpriteBatch.Draw calls or indirect calls through method calls from other classes that store a reference to the SpriteBatch object and then use its Draw method.

Another approach I see is that in these separate classes they call SpriteBatch.Begin and SpriteBatch.End before their drawing code in each of these classes and don't rely on already being contained within a drawing session (between a begin and end call).

My question is two-fold. Firstly, as the title suggests, what are the performance implications of calling SpriteBatch.Begin/End in all these separate classes so often (once per class per drawing update) versus just calling it the one time each update. Secondly, and this question is a a bit more subjective but, which design is generally preferable?

Thanks.


texts: What is the simplest algorithm or pattern to continues ground/Floor

texts:
Im beginner in 3d gaming , i have basic question not Language specific.
Say i have ground model for example terrain i modeled what is the common way to load the terrain  and use it again Or load another terrain when
the main model for example AirCraft im controlling in the game approaching its end , and i   want the player to see the terrain continue like in never ending world .


texts: Twin-stick controls for a cohesive group of agents

texts:
I'm trying to implement a classic twin-stick controller for a group of physics-based game objects. Here are the rules I'm trying to follow:

Agents always stay close to each other within a certain threshold.
Moving the left stick moves the entire group in that direction.
Moving the group on a collider like a wall will "compress" the group like a ball. Releasing the left stick will make the group recover its "natural" shape.

I tried a few things:

Classic steering with cohesion/follow behaviors: This kinda works, but when moving against a sharp corner, a part of the group will move on and separate from the others. Adjusting the steering weights in this scenario produces unnatural results, and the whole thing just feels too "floaty".
Softbody simulation: This works pretty well when moving on a corner, but you can really feel the springs between each agent. Again, it just feels wrong as a whole.
Box2D joints between each agent: Keeps all the agents tightly packed, but the group feels very rigid.

The solution might be a combination of the previous points, but I'm pretty sure I'm over-thinking this.


texts: Bold black bar on right side of game in Unity (Android)

texts:
I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone.

Here are the screenshots :

One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left.

Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go.

I hope I can get some help. Ask me if you need any piece of code.

EDIT :

"CameraFollow" script

 using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    public GameObject targetObject;
    private float distanceToTarget;

    // Use this for initialization
    void Start () {
        distanceToTarget = transform.position.x - targetObject.transform.position.x;

    }

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

        float targetObjectX = targetObject.transform.position.x;

        Vector3 newCameraPosition = transform.position;
        newCameraPosition.x = targetObjectX + distanceToTarget;
        transform.position = newCameraPosition;
    }
}

My "GeneratorScript"

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

public class GeneratorScript : MonoBehaviour {

    public GameObject[] availableRooms;

    public List<GameObject> currentRooms;

    private float screenWidthInPoints;

    // Use this for initialization
    void Start () {
        float height = 0.0f * Camera.main.orthographicSize;
        screenWidthInPoints = height * (Camera.main.targetDisplay);
    }

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

    }

    void FixedUpdate()
    {
        GenerateRoomIfRequred ();
    }

    void AddRoom(float farhtestRoomEndX)
    {
        int randomRoomIndex = Random.Range (0, availableRooms.Length);

        GameObject room = (GameObject)Instantiate (availableRooms [randomRoomIndex]);

        float roomWidth = room.transform.FindChild ("floor").localScale.x;

        float roomCenter = farhtestRoomEndX + roomWidth * 3.0f;

        room.transform.position = new Vector3 (roomCenter, 0, 0);

        currentRooms.Add (room);
    }

    void GenerateRoomIfRequred()
    {
        //1
        List<GameObject> roomsToRemove = new List<GameObject>();

        //2
        bool addRooms = true;

        //3
        float playerX = transform.position.x;

        //4
        float removeRoomX = playerX - screenWidthInPoints;

        //5
        float addRoomX = playerX + screenWidthInPoints;

        //6
        float farhtestRoomEndX = 0;

        foreach(var room in currentRooms)
        {
            //7
            float roomWidth = room.transform.FindChild("floor").localScale.x;
            float roomStartX = room.transform.position.x - roomWidth * 6.0f;
            float roomEndX = roomStartX + (roomWidth * 13.0f);

            //8
            if (roomStartX > addRoomX)
                addRooms = false;

            //9
            if (roomEndX < removeRoomX)
                roomsToRemove.Add(room);

            //10
            farhtestRoomEndX = Mathf.Max(farhtestRoomEndX, roomEndX);
        }

        //11
        foreach(var room in roomsToRemove)
        {
            currentRooms.Remove(room);
            Destroy(room);
        }

        //12
        if (addRooms)
            AddRoom(farhtestRoomEndX);
    }

}

(I tried playing with the numbers on GeneratorScript, but nothing seemed to help.


texts: Why do games run so much better in Windows than in OSX?

texts: For example, on my Mac Mini with Bootcamp, Team Fortress 2 runs at about 20fps in OSX and 80fps in Windows. This seems to be a common case. Why is this?


texts: Rotate object against Gyroscope in Unity

texts:
I would like to rotate a simple object against the z-rotation of the gyroscope of a smartphone, so that the object will always "look" to the physical floor where the user is standing. After that, I would like to translate that object forward. It should give you the feeling, that the object is attracted by the "real world" gravity.

Here's a small bad sketch I just made for better understanding:

I have already tried different examples I found on the web, but they were all kinda too complex for my purpose (they were all about rotating the camera in all 3 axes).

Has anyone ever made some simple script for something like that? Thanks for your help.

EDIT:

I have already tried some things out, I found a script on the web but it turned out to be "unprecise". I created a cube and attached the script to it, but when you rotate your phone by 180 degrees a few times, you will notice an "offset".

Here's the script:

public var gyroSensitivity : float = 50.0;
private var z : float;

function Update() {

    GyroRotation();

    //Move the object
    transform.Translate(0,-.03f,0);
}

function GyroRotation(){
    //get values from the gyroscope
    z = Input.gyro.rotationRateUnbiased.z;
    RotateZee(z);
}

function RotateZee(axis : float){
    transform.RotateAround(transform.position, new Vector3(0,0,1), -axis * Time.deltaTime * gyroSensitivity);
}

I'm pretty sure it has something to do with the gyroSensitivity, but I need to multiply the value with something or it will rotate only a few degrees.


texts: I've been using XNA for 2D games for awhile, and I am just learning 3D now. I have a question, which seems like it should be fairly basic. As I understand it, I make a model in Maya (or whatever) and have some animations in it (walk, jump, etc.). How do I take that model, and put it in my game, and have it run the animation to walk? Thanks!


texts:
I'm working on a little pong clone and trying to implement collisions using triggers.

I have a ball which OnTriggerEnter sends out a raycast from the ball's position towards its velocity. I then take the .normal of the raycast hit and use that to figure out bounce angle.

most of the time this is working, but in a few cases (I can't quite figure out the common element between them) It doesn't work and gives a completely wrong number.

Video example, https://webmshare.com/xAe7X

Full code,

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

public class BallScript : MonoBehaviour {
    public Vector2 velocity;
    public float angularVelocity;
    private Vector2 collisionNormal;

    void FixedUpdate(){
        transform.Translate (velocity.x, velocity.y, 0);
        Debug.DrawRay ((Vector2)transform.position - velocity * 2, velocity * 5,Color.red);
    }

    void OnTriggerEnter2D(Collider2D other) {
        FindCollisionNormal ();
        ReflectVelocity ();
    }

    public void FindCollisionNormal(){
        RaycastHit2D[] hits = Physics2D.RaycastAll ( (Vector2)transform.position - velocity * 2, velocity * 5);
        foreach (RaycastHit2D hit in hits) {
            if (hit.collider.GetType () == typeof(BoxCollider2D)) {
                collisionNormal = hit.normal;
                collisionNormal = new Vector2 (collisionNormal.y, collisionNormal.x);
            }
        }
    }

    public void ReflectVelocity(){
        print (collisionNormal);
        velocity = -velocity + 2 * (Vector2.Dot (velocity, collisionNormal) * collisionNormal);
    }
}


texts:
I'm working through the Head First Java book, and one piece of code it makes me write looks like this:

import java.io.*;
public class GameHelper {
    public String getUserInput(String promt){
        String inputLine = null;
        System.out.print(promt + " ");
        try {
            BufferedReader is = new BufferedReader(
                    new InputStreamReader(System.in));
            if (inputLine.length() == 0) return null;
        } catch (IOException e){
            System.out.println("IOException: " + e);
        }
        return inputLine;
    }
}

But eclipse tells me the exception is never thrown from the try statement, what does that mean?


texts: Are you supposed to be looping through all PhysicsObjects at every step in a physics engine?

texts:
I am currently making a small 2D game and I am trying to implement some basic 2D physics. I currently have  a list of around 100 PhysicsObjects which I loop through every frame in order to update and apply forces to that object based on user input. The basic code is as follows:
accumulator = 0
dt = 0.01

while running:
    for each object in PhysicsObjects:
        update object

    accumulator += time between last frame and current frame

    while accumulator >= dt:
        for each object in PhysicsObjects:
            resolve forces to get new position of object based on dt
        accumulator -= dt

    for each object in PhysicsObjects:
        render the object

I was going to resolve the forces and calculate the new position in the update method of each object, but I was told the dt was necessary in order to make the movement and physics independent of frame rate, which is why it is in a separate loop. I also can't update the objects in the physics engine loop as the update method needs to occur every frame.
This already seems incredibly inefficient, and I haven't even started to test for collisions or anything else more in the physics engine. Is there a better way to structure this where I don't need to loop through every object again in order to calculate their new position?


texts: Faster way to draw dynamic meshes in OpenGL ES

texts:
I'm writing a 3D game which is going to inlcude some dynamic meshes.

For now, my code looks like this :

private float[] mVertices;
private FloatBuffer mVertexBuffer;

public void onDrawFrame(GL10 gl) {
    // first clear the screen of any previous drawing
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

    // initialize the matrix
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();

    // update the vertex data
    for (int vtx = 0; vtx < mVtxCount; ++vtx){
        // fill in the x, y and z components of the vertex position
        mVertices[vtx * 3] = x;
        mVertices[(vtx * 3) + 1] = y;
        mVertices[(vtx * 3) + 2] = z;
    }

    // update the vertex buffer
    mVertexBuffer.clear();
    mVertexBuffer.put(mVertices);
    mVertexBuffer.position(0);

    // render the vertex buffer
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
    gl.glDrawElements(GL10.GL_LINES, mIndices.length,
                GL10.GL_UNSIGNED_BYTE, mIndexBuffer);
}

Here is an easy sample as the index buffer does not change so I only update the vertex position, normal and texture coordinates.

Of course I understand dynamic mesh will always be slower to render than static mesh, but I wonder if the method I use is good or if there is a faster / better way to do this .


texts:
I am currently developing an isometric tile game for android. I am currently working on how I  to handle rendering the tiles in an efficient way. So I was wondering about the possibility of using a small set of grey-scale tile images with different coloured overlays, rather than many coloured tile images.

Has this been done before? Is it do-able in android? How would it affect efficiency?


texts: Animation is not starting even though collider is triggered?

texts:
progress is steady but it is a bumpy road. I have removed the animation script from my character and reworked it into the controller script. I have also added new animations. Doing this required replacing the character FBX I was using earlier.

Doing this has caused an unexpected problem: Remember that super-cool item box that I made, that the character can trigger when he jumps under it, causing it to play an animation where the lid pops off?  Well, that's broken now. The box's idle animation still plays, but the GetItem animation does not.  Before importing the new character, his animations and the box's animations were in the same animation controller. I separated them into their own controllers, and applied them each where they belong. I did not make any more changes ( you can see all its properties in the demos below). There are still no transitions or parameters for the ItemBox. Funny enough, I tested it and the ItemBox's trigger is being activated. What could be wrong?

Video links (SHORT):

Link to video of new character demo

Link to Animators Panels Video

How can I get the GetItem animation to play for my itemBox again?

whoops, here is the relevant script:

ItemBox.cs:

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

public class ItemBox : MonoBehaviour
{
    // Start is called before the first frame update

    bool disabled = false;
    Animator anim;

    void Start()
    {
        anim = GetComponentInChildren<Animator>();
        if (!disabled)
        {
            anim.Play("ItemBox_Idle");
        }
    }

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

    }

    void OnTriggerEnter (Collider other)
    {
        if (!disabled && other.gameObject.tag == "Player")
        {
            print("itembox triggered");
            anim.Play("ItemBox_GetItem");
            disabled = true;
        }
    }
}

**This is the heirarchy for the ItemBox prefab. Notice that animation frames can only be seen from first child ("Parent") of that prefab, downward: **

UPDATE! GetItem animation is playing in the animation graph while I play the game, hitting the box from below, but the animation doesn't play in the game!  The plot thickens!  See (shorter) video:

shorter video


texts: XNA GameTime TotalGameTime slower than real time

texts:
I have set-up an empty test project consisting of a System.Diagnostics.Stopwatch and this in the draw method:

spriteBatch.DrawString(font, gameTime.TotalGameTime.TotalSeconds.ToString(),
new Vector2(100, 100), Color.White);

spriteBatch.DrawString(font, stopwatch.Elapsed.TotalSeconds.ToString(), new
Vector2(100, 200), Color.White);

The GameTime.TotalGameTime displayed is slower than the stop watch (by about 5 seconds per minute) even though GameTime.IsRunningSlowly is always false, why is this?

The reason this is an issue is because I have a server which uses stopwatch and it is faster than my client game. For instance my client notifies the server it has dropped a mine which explodes in one minute. Because the stopwatch is faster the server state explodes the mine before the client and they are out of sync. I don't want to have to notify the client when the server explodes it as this would use unnecessary bandwidth.


texts: If I own the rights to a third party game on a defunct console, can I republish it without the permissions of the console manufacturer?

texts: Suppose I owned the rights to a third party game published on the NES. Could I make a ROM of it and sell the emulated version?


texts: JNI Error when Wrapping Jar with JOGL using Launch4j

texts:
I have been trying to wrap my fat JAR file into an EXE using Launch4j, but I have been running into problems when I try to execute the EXE. Here is the error log I get from Launch4j:

Executing: E:\Downloads\CasualCaving.exe
JNILibLoaderBase: Caught IllegalArgumentException: No Jar name in <jar:file:/E:/Downloads/CasualCaving.exe!/jogamp/common/Debug.class>
Exception in thread "main" java.lang.UnsatisfiedLinkError: Can't load library: E:\Downloads\natives\windows-amd64\\gluegen-rt.dll
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.load0(Unknown Source)
    at java.lang.System.load(Unknown Source)
    at com.jogamp.common.jvm.JNILibLoaderBase.loadLibraryInternal(JNILibLoaderBase.java:624)
    at com.jogamp.common.jvm.JNILibLoaderBase.access$000(JNILibLoaderBase.java:63)
    at com.jogamp.common.jvm.JNILibLoaderBase$DefaultAction.loadLibrary(JNILibLoaderBase.java:106)
    at com.jogamp.common.jvm.JNILibLoaderBase.loadLibrary(JNILibLoaderBase.java:487)
    at com.jogamp.common.os.DynamicLibraryBundle$GlueJNILibLoader.loadLibrary(DynamicLibraryBundle.java:421)
    at com.jogamp.common.os.Platform$1.run(Platform.java:317)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.jogamp.common.os.Platform.<clinit>(Platform.java:287)
    at com.jogamp.opengl.GLProfile.<clinit>(GLProfile.java:147)
    at org.graphics.Render.<init>(Render.java:20)
    at org.engine.Main.main(Main.java:18)

I am using JOGL 2.3.2 imported through Maven, with the assembly plugin to compile it to a fat JAR. Here is a picture of my library configuration:

I am not sure what is wrong, as the JAR file works fine.


texts:
var cw = window.innerWidth;
        var ch = window.innerHeight;
        var game = new Phaser.Game(cw, ch, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });

        function preload() {
            game.load.tilemap('Background', 'https://gist.githubusercontent.com/anonymous/c61b37df015a0b2af1d7/raw/172bf9c2d4c20c56699eacce263525409caaf743/54996634e4b0a35d00c9b516.json', null, Phaser.Tilemap.TILED_JSON);
            game.load.image('tiles', 'http://i.imgur.com/gmWQIFK.png');
            game.load.image('player', 'http://i.imgur.com/tCCrLyh.png');
        }

        var map;
        var layer;
        var player;
        var _keyboard;
        var playerJumping;
        function create() {
            player = game.add.sprite(0, ch - 32, 'player');
            game.world.setBounds(0, 0, cw, ch);
            game.physics.startSystem(Phaser.Physics.ARCADE);
            game.physics.arcade.gravity.y = 300;
            game.physics.enable(player, Phaser.Physics.ARCADE);
            player.body.collideWorldBounds = true;
            game.stage.backgroundColor = '#787878';
            map = game.add.tilemap('Background');
            map.addTilesetImage('smb_tiles', 'tiles');
            layer = map.createLayer('Tile Layer 1');
            layer.resizeWorld();

            _keyboard = game.input.keyboard.createCursorKeys();
            game.camera.follow(player);
        }
        function update()
        {
            player.body.x += 2;
            if (_keyboard.up.isDown && player.body.onFloor()) {
                playerJumping = true;
                player.body.velocity.y = -2;

            }
            else {
                playerJumping = false;
            }
        }

As you can see the tiled Map start at a height of 320px bcs originally the map have this height  and if I change the game height to 320px everything works fine , but my question is if i want to make the tiledMap responsive to innerHeight and width for the screen how can i do this so the tiled map start at the bottom of the screen and not at the 320px

you can see how the tiled map layer is starting in the middle of the screen . is there by any chance something i can do to make it start at the bottom of the screen


texts: What's wrong with my method of getting intermediate rendering to my postprocessing shader?

texts:
I'm working on a project in OpenGL. Earlier this week, I successfully implemented Deferred Shading, but I'm not sure how to pass the information from the Deferred Shader to the Post Processing Shader.

glBindFramebuffer(GL_FRAMEBUFFER, fboId);
glViewport(0, 0, int(ScreenSize.x), int(ScreenSize.y)); // Render on the whole framebuffer, complete from the lower left corner to the upper right

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

//...Drawing for Opaque objects, pass all transparent objects to a seperate texture
//after having drawn them using Forward Shading

//glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, int(ScreenSize.x), int(ScreenSize.y));

// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

// Use our shader
glUseProgram(quad_programID);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gBuffTextures[0]);
glUniform1i(gBuffPosnID, 0);

//More Textures

//Uniforms

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 2*3 indices starting at 0 -> 2 triangles

glDisableVertexAttribArray(0);

So far this works just fine. Now here's the difficult part - passing the final image to the post processing shader.

glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, int(ScreenSize.x), int(ScreenSize.y));

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glUseProgram(post_programID);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, gBuffTextures[0]);
glUniform1i(UniformPostImage, 0);

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, gBuffDepthTextures);
glUniform1i(UniformDepthImage, 1);

glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, dirt);
glUniform1i(UniformDirtImage, 2);

glUniform1f(UniformTime, (float)currentTime);

glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // 2*3 indices starting at 0 -> 2 triangles

glDisableVertexAttribArray(0);

I'm loading the image from the deferred shader normally, and passing it using:

layout(location = 0) out vec3 image;

All I recieve is the first texture I pass, the position shader. Can anyone tell me how to pass the image from the deferred shader to the post processing shader?


texts: Game Development at iOS+Android Platform : Template Engine for UI

texts:
We have broken down our game development process to

UI Programming
Core Game Programming
Particle Effect Programming

UI will be created by a group of programmers and those UI will be used at Core Game Programming.

For example, at web applications, there are several template engine available, for example Smarty.

Is there any Template engine for UI for Game Development


texts:
I'm trying to scale my window, for example from 440*420 to 320*240.

How can I easily do this?


texts: I'm working on a 3D real time tactics wargame and a primary feature is military customisation. As part of the customisation, I would like to have the player be able to change some of the colors of the unit's texture, similar to how Dawn of War has their color changer. How did they do this?


texts:
I have a matrix of pixels in RAM memory, e.g. 1000x1000 pixels. I send it to GPU using

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1000,1000, 0, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

Which works great. But then I change some pixels, located in rectangle x=50, y=50, width =100, height=100. Sending the whole 1000x1000px picture again takes too much time, I would like to send only changed sub-area to the GPU.

I have tired

gl.texSubImage2D(gl.TEXTURE_2D, 0, 50,50, 100,100, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

but it seems, that parameter "pixels" should be the sub-area of 100x100 pixels. Copying out a sub-area from a large picture also takes too much time. Can I somehow specify a sub-rectangle for source pixels in RAM? Maybe somehow using gl.pixelStorei() ?

UPDATE: I discovered that it is possible in WebGL 2.0 (= OpenGL ES 3.0) using gl.pixelStorei() by changing  PACK_ROW_LENGTH, PACK_SKIP_ROWS, PACK_SKIP_PIXELS  parameters. Too bad WebGL 2.0 is not supported in most of devices now :(


texts: How can I show xna graphics content in a control on a form in xna?

texts:
I was able to create a form in xna using "Add Windows Form", named "Form1" then adding:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

How can I add graphics to some control, perhaps a picturebox, on Form1 that could potentially show my game as in a level editor?

Thanks.


texts: Using a state pattern across multiple controllers / general architecture advice

texts:
I'm trying to implement a state pattern - having skated by with enums forever - and have hit a bit of a wall when it comes to it's implementation in my game. It's a grid based strategy game with an MVC hierarchy.

The general flow is InputManager -> CursorManager -> GridManager. So if the player presses "Up", the InputManager will translate that to the appropriate action and notify the CursorManager. The CursorManager will then update the cursor's world position and then then prompt the GridManager to find what's in the hex in order to update the UI with terrain/unit info.

My new addition is thus having the GridManager change the cursor's state depending on what's in the tile. You pressed up? Let's let the cursor state dictate what happens to the grid. So naturally I created a cursor state object in the CursorManager, but suddenly realized each state needed decent amount of shared information across different the two controllers.

For instance,

public class FreeCursor : CursorState
{
    public override void ActionPressed()
    {
        currState = gridManager.selectTile(cursor.position);
    }
}

So this means the FreeCursor state would need reference to the GridManager object, reference to the cursor GameObject, and also a reference to the current state itself. All 3 of those are already in the CursorManager, so it's no problem, just throw them all in a constructor: FreeCursor(CursorState context, GridManager gridManager, GameObject goCursor)

But d'oh, when gridManager.tileSelected() completes, it should return the new state. So the GridManager should be saying

public CursorState selectTile(Vector3 position) {
     //...
     return new FreeCursor(this);
}

...Except now we're missing the GameObject and the current cursor state, which aren't accessible in the GridManager.

So I could go one or two ways - make the GridManager also contain a reference to the context, so it becomes return new SelectedUnitState(this, CursorManager) and changes our flow to be InputManager -> CursorManager <--> GridManager. Or I could say screw it, throw the cursor state and GameObject into the GridManager and call it day.

...But both feel just wrong? The latter through combining two somewhat distinct controllers - the former by making the state be passed it's own containing object like a poor man's reflection or something. Because if I do that, I might as well just use Unity's GameObject.Find(Cursor). Am I wrong to think this? And if so, is the problem with my implementation of the state pattern or the way I've laid out my 'architecture'?

tl;dr: How do you handle a state pattern with data from multiple controllers?

Thanks!


texts: Multi-platform multi-threading: What are the real challenges?

texts:
While a library like SDL provides a cross-platform wrapper API for threading, I think it would be naive to assume that this leads directly to easy development of games across vastly different platforms (desktop / mobile).

What is the best way to tackle developing in this way (given any cross-platform threading API) considering the following:

different numbers of cores
vastly different processing capabilities per core
A generally different systems architecture with eg. different latencies for cache, RAM , and I/O access

I get the feeling that the only way to do this is evaluate how many threads may be run per each device you intend to support, and find out what the lowest common denominator is. However, this still leaves me in the dark as to the total amount of processing throughput available. Am I right in assuming the only way to do this effectively is to actively develop for the lowest spec mobile device I intend to support, throughout development? -- i.e. the lowest common denominator? Should this roughly be sufficient? Or is there more to it than this?

EDIT: Please could others offer further experience on this as I don't feel my question has been answered fully yet.


texts: How can I switch two GameObects in an array in Unity?

texts:
I'm putting together a match-3 as my first unity project and I'm having some trouble with switching two GameObjects.  I thought I had it working, but I was running into strange issues.  I hunted them down and found that my code below does NOT copy the script values of the original tiles when I instantiate them.

For instance, I switch a blue tile and a yellow tile.  All stuff directly in the object instantiate correctly (right place, right color tile), but the code in my script that determines which it should be goes back to the default so behind the scenes they both think they are red tiles.

void SwitchTile(Vector2 start, Vector2 end)
    {

        GameObject tempStart = (GameObject)Instantiate(tiles[(int)start.x, (int)start.y]);
        DestroyImmediate(tiles[(int)start.x, (int)start.y]);

        tiles[(int)start.x, (int)start.y] = (GameObject)Instantiate(tiles[(int)end.x, (int)end.y]);
        DestroyImmediate(tiles[(int)end.x, (int)end.y]);
        tiles[(int)end.x, (int)end.y] = (GameObject)Instantiate(tempStart);

        Destroy(tempStart);

    }

How can I clone a GameObject with all of it's components also correctly cloned in unity?  Or is there a better way of switching GameObjects in an array in unity?


texts: In tools development, what languages and technologies are currently in use?

texts:
I am an aspiring tools developer currently in university. Normally I use both C++ and C# to and from but as my time at university is coming to an end, what language and technologies are worth focusing on? With tools I'm not only thinking simple data-file editors, but level editors and such as well.

I have tried searching in numerous places but generally I only find questions regarding what language or tools to use for game development. As I want to create the tools rather than use them, the answers don't necessarily apply.

Seeing as C++ still seems to be the language of choice in the gaming industry, is it also still the primary language for tools? If so, what UI and core libraries are most prominent? wxWidgets and stl/boost? Plain Win32?

Or - if C++ is being phased out in favor of "easier" languages like C# - is WinForms the right pick, or is the industry moving towards WPF? Maybe scaleform internally as well?

In short, is there anything I absolutely need to know to not be just an expensive chair heater?


texts: Collision between Mesh Plane and 2D Sprite

texts:
I've just recently started programming using Unity and made a couple of games with it, I'm trying out more and more advanced stuff as I do more games, but right now...

I'm trying to make a game that's basically a way simpler clone of pokemon y/r/g/b (I'm only concerned about tile placement, player movement / collision, and dialogue boxes at this time)

I tried about 3 methods for tile placement and found that using a mesh worked best for me (using tiled and tiled2unity) and imported the tmx files into unity.

Now, I just dont know where to go from here.

Starting with the player, I don't want to add physics since most games like this doesn't really have physics involved. So I tried adding a box collider to the player then a controller that uses transform.translate. Unfortunately, I dont think the colliders work nicely with transform.translate.

In this scenario, is the best setup for the player simply just using a kinematic rigidbody2d then adding the code/methods to collide with the map? Also since translate might be a bad idea, is transform.position a better alternative to use? (note that the player moves in increments in a "tile-like movement", any comments or suggestions?)

I'm also quite surprised by the lack of simpler games such as this one. Most of the examples I can find online are physics based platformers and top-downs that use code like velocity, addForce, with physics components involved. Any available source code that I could study would be welcome.

(I've also posted this on Unity Forums but people frequent here more often)


texts: What is wrong with my vertex declaration?

texts:
What is wrong with my vertex declaration below? I am using it with instancing. After adding TextureInformation to it, it renders weird and has an epileptical seizure.

    public struct VertexInstance : IVertexType
    {
        public Matrix World;
        public Color Color;
        public Vector3 TextureInformation;

        // I use arithmetic here to show clearly where these numbers come from
        // You can just type 28 if you want
        public static readonly int SizeInBytes = sizeof(float) * 23;

        // Vertex Element array for our struct above
        public static readonly VertexElement[] VertexElements = {
            new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0),
            new VertexElement(sizeof(float) * 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1),
            new VertexElement(sizeof(float) * 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2),
            new VertexElement(sizeof(float) * 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3),
            new VertexElement(sizeof(float) * 16, VertexElementFormat.Color, VertexElementUsage.TextureCoordinate, 4),
            new VertexElement(sizeof(float) * 20, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 5)
        };

        public static VertexDeclaration Declaration
        {
            get { return new VertexDeclaration(VertexElements); }
        }

        VertexDeclaration IVertexType.VertexDeclaration
        {
            get { return new VertexDeclaration(VertexElements); }
        }
    }


texts: How do I download audio resources and save them in cache?

texts:
I am developing a game in Unity3d 2019, the instructions of the game must be translated into several languages. Right now, they are part of the compilation, but this makes the compilation very large.

I would like, according to the selected language, to be able to download the corresponding audio and save it in the cache.


texts:
I'm trying to create a tile map with simple 2d images (30x30). I restarted the project from my previous post, and instead of using someone else's code, i though I would learn more to start from scratch. It was going well, but I ran into a bump when attempting to use images for tiles. My previous project used to following to create simple cubes. Now I'm trying to use images, and was wondering if there is a way to make the images wihtout having to follow the exact same steps as below:

function renderLevel(){
// clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// walls = red boxes
context.fillStyle = "#ff0000";
for(i=0;i<levelRows;i++){
    for(j=0;j<levelCols;j++){
        if(level[i][j]==1){
            blockrow.push(i);
            blockcol.push(j);
            context.fillRect(j*tileSize,i*tileSize,tileSize,tileSize);
            console.log("add");
            //collision[i] = new Array ([i],[j]);
        }
    }
}
// player = green box
context.fillStyle = "#00ff00";
context.fillRect(playerXPos,playerYPos,tileSize,tileSize);

}

Currently, I'm trying to simply drop the images, and manually declare the sizes when calling them.

    function setmapimages(){
    for (i=0;i<mapArray.length; i++){
        for (k=0; k<mapArray[i].length; k++){
            //image for player
            if (k==positionX && i==positionY){
                ctx.drawImage(img, 30, 30);
            }
            //image for road
            if (mapArray[i][k] == 0){
                ctx.drawImage(img2, 30, 30);
            }
            //image for collision
            if (mapArray[i][k] == 1){
                ctx.drawImage(img3, 30, 30);
            }
            //image for Store
            if (mapArray[i][k] == 2){
                ctx.drawImage(img4, 30, 30);
            }
        }
    }
};

I set the canvas size similarly to the previous project:

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
canvas.width =img.width*11;
canvas.height =img.height*9;

Although I set the variables a bit different. Since I'm using images now.

var img = new Image();
img.src= "image.png";
var img2 = new Image();
img.src= "image2.png";
var img3 = new Image();
img.src= "image3.png";
var img4 = new Image();
img.src= "image3.png";

Am I calling the images correctly? I looked up "drawimage" and think I went the wrong way with this, but I'm unsure what could call the images correctly.


texts:
I have a circular shape object, which I want to rotate like a fan along it's own axis.
I can change the rotation in any direction i.e. dx, dy, dz using my transformation matrix.
The following it's the code:
 Matrix4f matrix = new Matrix4f();
 matrix.setIdentity();
 Matrix4f.translate(translation, matrix, matrix);
 Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix);
 Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix);
 Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix);
 Matrix4f.scale(new Vector3f(scale,scale,scale), matrix, matrix);

My vertex code:
 vec4 worldPosition = transformationMatrix * vec4(position,1.0);
 vec4 positionRelativeToCam = viewMatrix*worldPosition;
 gl_Position = projectionMatrix *positionRelativeToCam;

But, it's not rotating along its own axis, it is flipping like a coin instead. What am I missing here?


texts: Can't click on a button with startDrag() active on stage

texts:
I need to know how can I enable mouse click on a button when I have a MouseEvent listener for the stage.

I have an MClip associated with the mouse cursor:

Mouse.hide();
scope.startDrag(true);

And a MouseEvent on the stage:

stage.addEventListener(MouseEvent.CLICK, FunctionXYZ);

When I try to click on any button they don't call the function that I create for those buttons... for example, button for fullscreen, exit, help, etc... What can I do?


texts: Is there a 3D equivalent of hex tile maps?

texts: Probably the biggest advantage of a hex-based versus square-based map tiling is that the center of each hex has the same distance to all its neighboring hexes. Is there a similar shape that tiles this way in 3D, and an engine that supports such a model?


texts: Collision doesn't work in isometric view

texts:
I have problems with collision detection in my isometric game - the collision is on a different spot then the actual object is, its like the SDL_Rect  is somewhere else then the object itself which is impossible.
I checked the values with the debugger it seems there is everything right.

My player has Isometric movement. This is the calculation for the screenworld to isometric

Vector2 Vector2::PosToIso()
{
    return Vector2(x - y, (y + x) / 2);
}

When the player doesnt have the isometric movement the collision works fine.
I tried to calculate the the objec's x and y pos to iso and i tried with the normal 2D screen values same result.

Collision code:

    bool checkCollision( SDL_Rect a, SDL_Rect b )
{
    int leftA, leftB;
    int rightA, rightB;
    int topA, topB;
    int bottomA, bottomB;

    leftA = a.x;
    rightA = a.x + a.w;
    topA = a.y;
    bottomA = a.y + a.h;

    leftB = b.x;
    rightB = b.x + b.w;
    topB = b.y;
    bottomB = b.y + b.h;

  if( bottomA < topB )
    {
        return false;
    }

    if( topA > bottomB )
    {
        return false;
    }

    if( rightA < leftB )
    {
        return false;
    }

    if( leftA > rightB )
    {
        return false;
    }
    return true;
}


texts: What are some ways to separate game logic from animations and the draw loop?

texts:
I have only previously made flash games, using MovieClips and such to separate out my animations from my game logic. Now I am getting into trying my hand at making a game for Android, but the game programming theory around separating these things still confuses me. I come from a background of developing non game web applications so I am versed in more MVC like patterns and am stuck in that mindset as I approach game programming.

I want to do things like abstract my game by having, for example, a game board class that contains the data for a grid of tiles with instances of a tile class that each contain properties. I can give my draw loop access to this and have it draw the game board based on the properties of each tile on the game board, but I don't understand where exactly animation should go. As far as I can tell, animation sort of sits between the abstracted game logic (model) and the draw loop (view). With my MVC mindset, it's frustrating trying to decide where animation is actually supposed to go. It would have quite a bit of data associated with it like a model, but seemingly needs to be very closely coupled with the draw loop in order to have things like frame independent animation.

How can I break out of this mindset and start thinking about patterns that make more sense for games?


texts: How can I use vibration of an iPhone for my HTML / Javascript game?

texts: I'm building a web game. I'm trying to use the iPhone's vibration functionality. How would I go about doing this seeing I want to package and deploy this game to the App Store. Is there a secured way to do this?


texts: Box2D: Adjusting character position for side-scrolling

texts:
In my side-scroller I would like to give the illusion of the character walking forward while his sprite is actually being held in place. If he walks near the edge of the screen, I would like to adjust his position at each step so that he is remaining still while the background moves backwards at the same rate he would have been moving. I think you get what I mean.

I figured that a simple case of "position = position - velocity" would do the trick, but then I realized it is not quite that easy with box2d. Velocity is expressed not at distance per frame, but distance per second. So instead I am essentially using position = position - velocity/60 since my game refreshes (or attempts to refresh at) 60 frames per second. But I can still see some lilting in the character's movement, and if I monitor his position, it shows that it indeed changes, most likely due to variations in frame rate.

Is velocity/60 the best I can hope for, save for hard coding the stop positions?

I am using the newest release of Box2Dweb. Yes, the javascript one. Here's a sample of the code:

var posX = this.body.GetPosition().x;
var posY = this.body.GetPosition().y;
var velX = this.body.GetLinearVelocity().x;

if(posX > 21 || posX < 12){
    screen.pos -= velX;
    this.body.SetPosition(new b2Vec2(posX - (velX/60),posY));
    }

I realize I can hardcode the positions like this:

    if(posX > 21) {
        screen.pos -= velX;
        this.body.SetPosition(new b2Vec2(21,posY));
    } else if(pos < 12){
        screen.pos -= velX;
        this.body.SetPosition(new b2Vec2(12,posY));
    }

But I'm not super excited about how decidedly undynamic that option is.


texts: Displaying total playing seconds at end of game

texts:
Creating a simple survival game.

When the player has been caught I want to display the amount of seconds that they survived for.

How do I go about this?


texts: How to get a pixel color from a specific sprite on touch (unity)?

texts:
I have a 2 layers of a different sprites. How can i get a pixel color from lower sprite?

I know how to get touch and world coordinates, but i have no idea what to do next.

Touch touch0 = Input.GetTouch(0); // screen touch coordinates
Vector2 playerPick = GetComponent<Camera>().ScreenToWorldPoint(touch0.position); // world coordinate


texts: How do I make a more or less realistic water surface?

texts:
I want to make a similar water surface like in this picture:

I need the water surface in the same view than in the picture. Is it possible to work without shaders?
I want to develop a little game for Xbox Live Indie Marketplace, Windows Phone and maybe later iPhone/iPad.

How should I make the water surface, so that it works on multiple platforms?


texts: How to make a 2D semicircle sprite in Unity?

texts:
I followed this answer: https://answers.unity.com/questions/1008644/semi-circle-2d-collider.html and was able to create a semicircle collider:

But is there any way I can just crop the circle sprite to make it a semicircle?

I tried looking for other documentation, but couldn't find any..


texts:
I've started making a browser-based game, as a hobby, where users log in via a website and can manage a soccer team. I need to have some sort of process running to handle player development, running matches, age players, generally progressing time..

I've never done anything like this before and therefore I'm putting this out there to get some feedback from other people.

So, my idea was that I could have a continuously running application which can handle all the "off-line" processing. But, that got me thinking that another approach could be to have, f.ex. a "PlayerTrainingTask" running daily, a "RunMatchesTask", running on a fixture-based schedule, et.c.

Which approach is most appropriate? or is there another option I haven't thought of?

What are your thoughts?


texts: Are the sides of a beveled rectangular prism considered "ngons", to be avoided?

texts:
Many tutorials I have watched say that everything should be made in 'quads' (ie. no triangles, and no ngons).

I think this is mainly due to getting into this habit so that if I make a complex model, eg. a rigged character face, then there won't be any animation issues like model warping or bad occlusions/shadows/etc. (please do correct me if this is wrong, its just what I've gathered from many videos and some books).

So I tasked myself with making a  Glock handgun, thinking this boxy shape might be a good starter project. I noticed the corners of the top piece are curved/beveled, so I beveled it on my model.

This is where I got my first problem though, the bevel process created about 3 new vertices on each corner I applied it to, but then this leaves the side of the piece with more than 4 edges (see picture):

In the pic you can see I highlighted one of the small 'edges' the bevel created. So now I can count something like 12 edges in total surrounding that side part.

Is that an ngon? Will it matter? And if its not OK, how should I do it?


texts:
Is it possible to prevent the collider 2D outline from hiding in Unity?
I am creating some animations in Unity. To create animations I select different parts of a hero and move them frame by frame. Now I am working on the run animation and would like to see the bottom collider during parts movement for the animation creation.
In my case the collider outline is red:

I don't want the red bottom line (which is the collider outline) to disappear while I am creating animations. Should I research the Unity extensions and maybe write my own which would prevent the collider from hiding or is it possible to achieve what I want out of the box somehow?


texts: How to orbit an object around another object in an oval path in Unity?

texts: I would like to create kind of planetary orbit structure for my game. I was used transform.RotateAround(Vector3.zero, Vector3.forward, RotationAngle * Time.deltaTime); and it rotates in a circular shape. But I would like to do it in an oval (Ellipse) shape.


texts: Unable to open project from a scene.unity file

texts:
The tutorial I'm following has provided its project files, and I'm trying to open them in Unity. Here is the project download link. You can also go to the tutorial webpage and scroll down to download.

I can't figure out how to do it. Here is what I've done.

a) Extract zip to my Unity Scenes/ folder.

b) Open Unity, create a new project called tutorial

c) File -> Open Scene -> navigate to Unity Scenes/voxeltut3/scene.unity

d) Click Open

It opens.. but then I don't see any of the tutorial's files in my project. There's none of the c# scripts, no art, no prefabs... It's just the original empty project that I created.

I also tried importing it as a new package:

e) Assets -> Import New Asset... -> select Unity Scenes/voxeltut3/scene.unity

f) Click Import

And nothing happens. The Import New Asset dialogbox is still open with the scene.unity selected. It's like it's telling me that I've selected an invalid file. So I guess this is wrong?

How do I open this tutorial project? I'm using unity 5.3.2

This is the folder structure the new Unity project that it created for me:

C:\Users\me\Documents\Unity Scenes

tutorial/
    Assets/
    Library/
    ProjectSettings/

I unzipped the tutorial files in

C:\Users\me\Documents\Unity Scenes

voxeltut3/
    Materials/
        tiles.mat
        tiles.mat.meta
    Block.cs
    BlockAir.cs
    BlockGrass.cs
    scene.unity
    ... (other files)


texts: How to create a map-like (clouds) texture

texts:
If you place a map of the world on a sphere, it will look like the image is continuous. Basically the left end of the image is sort of a continuation of the right end. You won't be able to see any cuts.

I'm trying to create a clouds texture to add to my planet such that it will seem it has clouds. I managed to create the clouds in GIMP, however, I can't figure out how to make sure the left end of my image is a smooth continuation of the right end. For example if you were to map the below image to your sphere (I removed transparency to make it clearer), there would be a very obvious transition from the right end of the image back to the left end on your sphere. How would I create a texture such that I get rid of that?

Sorry for my lack of terminology.


texts: How to create a forest game scene in unity3d?

texts:
I am pretty new to game development. I have started using unity3d.

I have created simple games for which I have used plane (3d gameObject). Now, I want to move a step forward I want to create a forest with mountain and trees. So, I went through few tutorials and concluded terrain (3d Object) will be best fit.

Issue: My player falls down from the terrain due to gravity and if i disable gravity then my player flies up in y axes when moved over mountains. What is the way i can create terrain with gravity and so that my player doesn't fall from the terrain.

Can anyone throw light on how do overcome above mentioned issue.


texts: How can I make trailing ghost effect (3d game)?

texts:
I'm trying to draw previous frame of animation on screen
you can see this effect here: https://youtu.be/WNL_KJNl6pU
Mortal Combat X (left) , Street Fighter Alpha 2 (right):

This effect also found in animation software and called onion skinning:

I've implemented this by spawning object every second but I think It is possible with shader.

Update
I could make this effect by using RenderTexture for capturing previous frame , but I can't remove background color :(
I tried with Blending and grab pass but don't work(it was rendered normally)!!
sources :
https://github.com/smkplus/TrailingFX
https://unitylist.com/r/4tp/unity-fluid-2d-blur-image-effect


texts:
I'm having trouble getting my button to appear correctly, as you can see in the image below, the right and top sides are stretched out and not displaying properly. I cannot figure out if this is a problem with the image itself or something wrong in the way I'm setting up the button.

Here are the settings in the inspector window:

Here is the original image:

UPDATE: So everything looked fine when I just opened up Unity, so I tried to figure out what I did last time for it to make this switch. It happens when I build and export the scene to my Android device.


texts: DirectX 11 - Get the world matrix of my camera

texts:
I'm relatively new to the world of 3D games programming and I am not sure if I am understanding some key concepts correctly.

Right now I have created a sphere that is 2.0f in radius which surround the camera to act as a sky box ( I disabled culling to ensure that it did not block structutes in my world, and then turned culling back on once it was drawn ), its position is currently relative to the world, which is a problem.

The problem is that when I walk over terrain my camera exits the 2.0f sphere causing me to see the default black colored sky, in order to solve this I think I need to move the sphere relative to the cameras world matrix.

I currently have this function, which takes in the master WVP matrices with an output parameter for the cameras world matrix:

void Camera::GetWorldMatrix(D3DXMATRIX w, D3DXMATRIX v, D3DXMATRIX p,
                            D3DXMATRIX& camWorld)
{
    // How can I determine the cameras world matrix here?
}

How I get the cameras world matrix relative to the master world matrix?


texts: XNA Adding Craters (via GPU) with a "Burn" Effect

texts:
I am currently working on a 2D "Worms" clone in XNA, and one of the features is "deformable" terrain (e.g. when a rocket hits the terrain, there is an explosion and a chunk of the terrain disappears).

How I am currently doing this is by using a texture that has a progressively higher Red value as it approaches the center. I cycle through every pixel of that "Deform" texture, and if the current pixel overlaps a terrain pixel and has a high enough red value, I modify the color array representing the terrain to transparent. If the current pixel does NOT have a high enough Red value, I blacken the terrain color (it gets blacker the closer the Red value is to the threshold). At the end of this operation I use SetData to update my terrain texture.

I realize this is not a good way to do it, not only because I have read about pipeline stalls and such, but also because it can become quite laggy if lots of craters are being added at the same time. I want to remake my Crater Generation on the GPU instead using Render Targets "ping-ponging" between being the target and the texture to modify. That isn't the problem, I know how to do that. the problem is I don't know how to keep my burn effect using this method.

Here's how the burn effect looks right now:

Does anybody have an idea how I would create a similar burn effect (darkening the edges around the formed crater)? I am completely unfamiliar with Shaders but if it requires it I would be really thankful if someone walked me through on how to do it. If there are any other ways that'd be great too.


texts:
I am currently working on an iOS project called Old Frank that I have been trying to follow a MVC design pattern.

The gist of it is.

GameObjects(model) <- Scene(controller) -> Sprites "SpriteKit" (View)

Now if I understand MVC correctly you can't use a lot of the features that SpriteKit has to offer if you want to follow MVC. For instance any SKAction, collision detection, etc.

Isn't it up to the model where game objects are located and how they should react when touching other objects? Isn't it up to the model to determine location over time?

Are there any parts of SpriteKit that would be considered okayto use as the "view" in MVC other than rendering?


texts:
… and no, I do not mean System-on-a-Chip.

I stumbled upon this question which was using the acronym in the context of graphics, and found myself wondering about its meaning. Neither the question nor the answer further explained the acronym, and a search on google only got me "system-on-a-chip", which I was already familiar with, and "security operations center", which I was less familiar with.

What does SoC stand for in the context of game development (and/or software engineering)?


texts: Generate a range of number with X being returned most of the time

texts:
I am attempting to write a RNG which returns a normal-like curve. For example, say I define X to be 4, I would like to generate a range of numbers from 1 to 8, but with 4 being returned most of the time (say 60%).

How can I accomplish this in a way I can easily define X, and the range of the numbers?


texts:
I'm moving my sphere on the screen using this method:

Matrix4 m = myBall.body.getCenterOfMassTransform();
Vector3 translation = new Vector3();
m.getTranslation(translation);

float multiplier = delta * 4 * game.platform.accelerometerFactor();
movement = new Vector3(Gdx.input.getAccelerometerY() * multiplier, 0, Gdx.input.getAccelerometerX() * multiplier);

translation.add(movement);
m.setTranslation(translation);
myBall.body.setCenterOfMassTransform(m);

Then I would like to rotate my sphere during movement. So I counted angle which sphere should be rotated and then applied it before I call myBall.body.setCenterOfMassTransform(m) using:

float x = movement.x;
float z = movement.z;
Vector3 axis = new Vector3(z, 0, -x);
m.rotate(axis, angle);

But the sphere is rotating strangely. Where is the problem in my process of rotation?


texts: Creating a 2D skeleton animation system for use with Panda3D

texts: Hey. I want to be able to create a system for 2D skeletal animation in my game. I'm using panda3d as my game engine. I'd like to be able to make simple bone structures and skin them with my sprites. I would prefer to do this with straight code and algorithms, but if I have to use a 3D modeler or something, then I can try to (I didn't do a great job last time I tried using Blender... >.<)


texts: Efficient type checking in collision detection

texts:
Basically, what's the most efficient and professional means of checking an object's type when it collides with another object. For instance (ignoring the math for collision detection), suppose we have a gameObject class that game objects inherit from and assume that there is a separate physics system that detects collisions for us, and then proceeds to call the colliding objects collideWithOther method, passing the other object involved in the collision into the method.

abstract class GameObject
{

    void abstract collideWithOther(GameObject gameObject);
}

class Bullet : GameObject
{

    void override collideWithOther(GameObject gameObject)
    {

    //Check other object to see if it has game logic related to collision with this object
    if (gameObject is Enermy)   //this is sudo code, the "is" keyword is to expensive for this.
    {
        //do bullet hit enermy code here
    }

    }
}

class Enermy : GameObject
{
...
}

I am aware that there is the "is" keyword and the the .getType meathod. However I have read that they are expensive and sloppy for a real time system such as a game.

To address some of the answers that this question might receive. In the example above we can simply cast the game object to bullet since we know that it would be that class. But the purpose of this question is for a situation where we don't which class it would be. As there may be 10 different classes that can all collide with the bullet, but only 2 of them have game logic associated with it. Also I know we can give the bullet different damaged as an member based on what type of the bullet it is, but that misses the point of the question as this between any object. What would be the most professional and efficient way of dealing with this.


texts: How can I optimise my game and its game objects?

texts:
I have a 3D game in Unity and I use blender to design models for it. My game has a feature where if you click a button, an object is cloned. An example from my game is a tree that is cloned around 100 times with different sizes and positions to form a forest.

The issue is that after a few presses of the button, the game starts to really lag. Is there a way to optimise the game in Unity or optimise the models in Blender to reduce this lag? I use the instantiate function in Unity to do my cloning.

Some useful information for a generic gameobject (all of them are similar in complexity):

faces: 12,226
triangles: 26,116
memory: 13.24 mb
gameobjects in scene not static
CPU usage mostly spent on rendering

Here is a screenshot showing my game running, where the blue part on the graph in the middle is when I click the button:

Here is a detailed look into the spikes you can see:


texts: Code reuse for a CRPG data model on the server-side

texts:
I'm working on a turn-based game with CRPG (Computer RPG) elements in HTML5. It has to support 10K+ CCUs (Concurrently Connected Users).
The CRPG elements in the game are item and character systems:

The game has characters, characters have items.
Items may be worn or used as consumables.
Items may be crafted and upgraded.
Characters gain experience and get new levels.
Characters and items have characteristics (like health, attack strength etc.).
Characters may have buffs and debuffs placed on them that affects characteristics.
Characters have talents that acts like permanent buffs or debuffs.
Items worn and consumables used may affect character characteristics.
Characters may strike each other, and strike outcome is calculated based on the effective characteristics of the attacker and target.

All of the above has to be stored and handled on the server-side.
To avoid developing everything from scratch for the 100th time, I'd like to maximize my reuse of existing code: original, free, or commercial.
I can adapt the CRPG model requirements to the implementation limitations to a certain (considerable) extent. Technology stack does not matter much either — as long as it is reasonably scalable.
How can I author my server-side solution to maximize code reuse?


texts: Shear transformation in the projection matrix?

texts: I am trying to understand what the shear transformation (l+r/r-l & b+t/t-b) is actually doing in the projection matrix? The only thing I got till now is headache :) Can you please help?


texts:
After a couple tries, I still haven't found any solution to this problem of mine.

Currently, I have a script inheriting from MonoBehavior which creates a map with Perlin Noise. Let's call it mapGenerator.
It instantiates a HexTile object from another script, which does not inherit from MonoBehaviour, that contains a refere to my terrain prefab and an enum value which says its type (so water, grass, wood, etc.). There is an array declared at the beginning of the script that I manually change as I'm adding terrains.

Everything works fine except when tweaking the map generation, If I want to change some values for perlin intervals, I might have to add another value to my HexTile[] and then drag my terrain prefab and set the enum value.

What I want is to know if there is a way to make the script select a prefab depending on the value the enum was set to.

Here is the code (simplified):

public class ProceduralTerrainGenerator : MonoBehaviour
{
public bool regenerateMap = true;

public Hextile[] hexTiles;

void Update()
{
    CreateMap();
}

private void CreateMap()
{
    // Some code for Perlin Noise generation inside perlinMap[,]
    for (int i = 0; i < mapLength; i++)
    {
        for (int j = 0; j < mapHeight; j++)
        {
            // Setting up position from i and j index
            foreach (HexTile hexTile in hexTiles)
            {
                if (ValueInRange(perlinMap[i,j], hexTile.LowLimit, hexTile.HighLimit)
                {
                    Instantiate<HexTile>(hexTile.tile, position, Quaternion.Euler(0f, 0f, 0f), this.transform);
                }
            }
        }
    }
}
}

and my other script

[System.Serializable]
public class HexTile
{
    public GameObject tile;
    public HexMetrics.HexType hexType;
    public float perlinNoiseLowLimit;
    public float perlinNoiseHighLimit;
}

=========== EDIT 1 ===========

I tried simplifing my problem, because I'm more interested in the concept, but here are more details.

I have a class named HexSettings, which contains the hex prefab (HexTile) named tile, its HexType, and the perlin noise bundaries.

[System.Serializable]
public class HexSettings
{
    public HexTile tile;
    public HexMetrics.HexType hexType;
    public float perlinNoiseLowLimit;
    public float perlinNoiseHighLimit;
}

Here is the HexType enum contained inside HexMetrics

public class HexMetrics
{
    // Hex metrics data for placement in grid data

    public enum HexType
    {
        GRASS,
        FOREST,
        WATER,
        SNOW,
        DESERT,
        LAKE
    }
}

What I would like is to have some soprt of dictionnary that contains the correct prefab according to the selected HexType.

As you can see in the image below, I can set my HexType to my terrain types, but I also have to set the HexTile object manually, where it could be set automatically according to the HexType value set. That is what I'm looking for.

I tried adding it in a dictionnary (something like Dictionnary<Hextype, HexTile>), looking for prefabs in my folder prefab with Resources.LoadAll<HexTile>("prefab");, no success, prefabs couldn't be loaded in HexSettings.


texts: What middle tier and backend libraries exist for handling player matching and out of game information?

texts: Are there any libraries or frameworks readily available that handle player metrics, rankings, matching, tournaments, etc? Anything for managing the player community? (Please don't say DotNetNuke)


texts:
I'm making space invaders (in OpenGL/SDL) and I've run into a problem
when trying to draw the sprite for the spaceship from the spritesheet.
In my entity class, I have a pointer for the sprite that belongs to the current instance of the object. In main, I make an instance on the heap of the
sheetSprite, passing in the u,v,width, and height of the sprite for
the parameters and then storing this reference in the mySprite field
of the spaceship entity.

The coordinates provided by the texture atlas are:                      <SubTexture name="playerShip2_green.png" x="112" y="866" width="112" height="75"/>

To draw the spaceship, I call the draw method from its "mySprite"
attribute. For some reason, only a white square is being rendered
without the actual texture. What could be causing the problem? The relevant code is below:

class SheetSprite {
public:

    SheetSprite(unsigned int textureID, float u, float v, float width, float height, float size, ShaderProgram program)
        :textureID(textureID), u(u), v(v), width(width), height(height), size(size), program(program) {}

    void Draw() {
        //glBindTexture(GL_TEXTURE_2D, textureID);
        glUseProgram(program.programID);
        GLfloat texCoords[] = {
            u, v + height,
            u + width, v,
            u, v,
            u + width, v,
            u, v + height,
            u + width, v + height
        };
        float aspect = width / height;
        float vertices[] = {
            -0.5f * size * aspect, -0.5f * size,
            0.5f * size * aspect, 0.5f * size,
            -0.5f * size * aspect, 0.5f * size,
            0.5f * size * aspect, 0.5f * size,
            -0.5f * size * aspect, -0.5f * size ,
            0.5f * size * aspect, -0.5f * size };
        glBindTexture(GL_TEXTURE_2D, textureID);
        //float vertices2[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5 };
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
        glEnableVertexAttribArray(program.positionAttribute);
        //float texCoords2[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
        glEnableVertexAttribArray(program.texCoordAttribute);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glDisableVertexAttribArray(program.positionAttribute);
        glDisableVertexAttribArray(program.texCoordAttribute);
    }
    float size;
    unsigned int textureID;
    float u;
    float v;
    float width;
    float height;
    ShaderProgram program;
};

class Entity {

public:
    Matrix modelMatrix, projectionMatrix, viewMatrix;
    float width, height = 1.0;
    float xDir, yDir = 0.0;
    float posX, posY = 0.0;
    float objSpeed = 0.0;
    float rotState = 0.0;
    float u, v, spr_width, spr_hght, spr_size = 0.0;
    unsigned int textureID;
    ShaderProgram program;
    //GLuint spriteSheetTexture = LoadTexture("sheet.png");
    SheetSprite* mySprite;

    Entity(float wid, float hght, float xDirect, float yDirect,
        float xPosition, float yPosition, float speed, float rState, ShaderProgram program) : width(wid), height(hght),
        xDir(xDirect), yDir(yDirect), posX(xPosition), posY(yPosition), objSpeed(speed), rotState(rState), program(program) {}

//Extra methods
};

//instantiation of sheetSprite in main

Entity spaceship(0.1f, 0.7f, 1.0f, 1.0f, -5.1f, 0.0f, 3.0f, 0.0f, program);
    spaceship.objSpeed = 10;

    GLuint spriteSheetTexture = LoadTexture("sheet.png");
    spaceship.mySprite = new SheetSprite(spriteSheetTexture, 112.0f / 1024.0f, 866.0f / 1024.0f, 112.0f / 1024.0f, 75.0f / 1024.0f, 0.7, program);

//in the game loop

spaceship.mySprite->Draw();


texts: How do I change the window position in Unrealscript?

texts:
So when I start my game it starts out in the middle of my screen at 1024x768 resolution, but then when I change the resolution via consolecommand("SETRES ..."); it resets the window position to the top left of my desktop.

Is there a way for me to set the windows position after I make this change?


texts: In Box2D, how can I get the compression force on a specific body?

texts:
I'm using Box2D. As you can see, there are three dynamic bodies connected to each other (think of it as a table from front view). LEG1 and LEG2 are connected to the static body (it's the ground body). Another dynamic body is falling onto the table.

I need to get the compression in the LEG1 and LEG2 separately.

Joints have a GetReactionForce() function which returns a b2Vec, which in turn has Length() and LengthSqd() functions. This will give the total sum of the forces in any taken joint. But what I need is forces in individual bodies that are connected with joints. Once you connect several bodies with a single joint it again will show the sum of forces which is not useful. Here's the case I'm talking about:


texts: How to make a bullet shoot in the direction of the gun in mobile?

texts:
I am working in unity with c#. I am working on a 2D platformer for mobile. The way I currently have it setup is one joystick that moves the charatcer makes the charatcer arm rotate and make the charatcer shoot the gun when pressed. Which all workd fine. But the problem I am having is the bullets from the gun are not going in the correct direction. Currently the bullets go to the rigtht no matter where I point the gun. I have tried in the raycats to use transform.right and transform.forward. All end up with the same result. the firepoint for the gun is an empty game object and the firepoint in the script is an tranfrom. It is an child of the gun so I thought it would use the same rotation but I am not sure of I need to say what rotation I need for the raycast. I tried changing it to an GameObject in the script but I got the same results. If someone could please help it would be grealty appreciated!!!

Here is the shoot function with the raycast.

public void Shoot ()
{
    Vector3 firePointPosition = new Vector3 (firePoint.position.x, firePoint.position.y, 0f);
    RaycastHit2D hit = Physics2D.Raycast (firePointPosition, firePoint.transform.right, 100, whatToHit, 0f);

    Debug.DrawLine(firePointPosition, (firePointPosition)*100, Color.cyan);
    if (hit.collider != null)
    {
        Debug.DrawLine(firePointPosition, hit.point, Color.red);
        Enemy enemy = hit.collider.GetComponent<Enemy>();
        if (enemy != null)
        {
            enemy.DamageEnemy(Damage);
            //Debug.Log("We hit " + hit.collider.name + "and did " + Damage + "damage");
        }
    }

    if (Time.time >= timeToSpawnEffect)
    {
        Vector3 hitPos;
        Vector3 hitNormal;

        if (hit.collider == null)
        {
            hitPos = (firePointPosition) * 30;
            hitNormal = new Vector3(9999, 9999, 9999);
        }
        else
        {
            hitPos = hit.point;
            hitNormal = hit.normal;
        }

        Effect(hitPos, hitNormal);
        timeToSpawnEffect = Time.time + 1 / effectSpawnRate;
    }
}

And here is the effect method

void Effect (Vector3 hitPos, Vector3 hitNormal)
{
    Transform trail = Instantiate (BulletTrailPrefab, firePoint.position, firePoint.rotation) as Transform;
    LineRenderer Lr = trail.GetComponent<LineRenderer>();

    if (Lr != null)
    {
        Lr.SetPosition(0, firePoint.position);
        Lr.SetPosition(1, hitPos);

    }

    Destroy(trail.gameObject, 0.04f);

    if (hitNormal != new Vector3(9999,9999,9999))
    {
        Transform hitParticle = Instantiate(HitPrefab, hitPos, Quaternion.FromToRotation (Vector3.right, hitNormal))as Transform;
        Destroy(hitParticle.gameObject, 1f);
    }

    Transform clone = Instantiate (MuzzleFlashPrefab, firePoint.position, firePoint.rotation) as Transform;
    clone.parent = firePoint;
    float size = Random.Range(0.6f, 0.9f);
    clone.localScale = new Vector3 (size, size, size);
    Destroy(clone.gameObject, 0.02f);

    //Shake the Camera
    camShake.Shake(camShakeAmt, camShakeLength);

    //Play shoot sound
    audioManger.PlaySound(weaponShootSound);
}


texts: Unusual Lighting Effects - Random Polygons Coloured

texts:
I am working on creating an object loader for use with iOS, I have managed to load the vertices, normals and face data from and OBJ file, and then place this data into arrays for reconstructing the object. But I have come across an issue with the lighting, at the bottom is a video from the simulation of my program - this is with the lighting in the following position:

CGFloat position[] = { 0.0f, -1.0f, 0.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, position);

This is specified in both the render method each frame and the setup view method which is called once at setup.

Various other lighting details are here, these are called once during setup:

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
CGFloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
CGFloat diffuseLight[] = { 1.0f, 0.0f, 0.0, 1.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
CGFloat position[] = { 0.0f, -1.0f, 0.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, position);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);

The video of the issue can be found here:

http://youtu.be/dXm4wqzvO5c

Thanks,

Paul

[EDIT]

Normals are also supplied by the following code, they are currently in a large normals array or XYZ XYZ XYZ etc...

// FACE SHADING
glColorPointer(4, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
glNormalPointer(GL_FLOAT, 3, normals);
glEnableClientState(GL_NORMAL_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, 3*numOfFaces);
glDisableClientState(GL_COLOR_ARRAY);

[ANSWERED!]

I have solved the issue but can't post the answer as I have too little reputation, but it was simply down to a typo!

glNormalPointer(GL_FLOAT, 3, normals);

should read

glNormalPointer(GL_FLOAT, 0, normals);

as all the normal data is in a single un shared array, so it does not need to skip values..


texts: What are "local" and "global" rotations?

texts:
Each node in jME3 has local and global rotations, which can be expressed in quaternions.

What are they?

Documentation has no clues, about in which state rotations are zero?


texts: Is it possible in HLSL to use bitfields?

texts:
I have in memory a representation of my 2d GameMap (think of a Scorched Earth like landscape).

The map is made up of MapElements, a MapElement is made up of 64 bits defined like

struct MapElement {
 uint Color;  // RGBA Color
 uint Info;   // info flags (collision, material etc)
}

MapElement Map[Height * Width];

Now I'm thinking of doing some effects in HLSL, for example lighting, that need per-pixel collision information.
Is there any way I can just upload the mapdata as I have it in memory, and use it in HLSL ?

So is there a way to in HLSL to sample Uploaded Map to see if (map[y*Height+Width] & CollisionFlag) != 0 ?


texts: Can I use a certain song in my credits as long as I credit the original author?

texts:
I am working on a commercial game and I'd like to use a certain song during the credit, because it would be very fitting for my particular game.

I know using music that other people made in your game can be illegal, but this is something pretty minor, and I was wondering how legal it is to use one of his songs, as long as I credit him (I understand most of you aren't lawyers but surely you can offer some examples or give a solid advice)


texts: What are the texture coordinates for a tetrahedron

texts:
EDIT This is the WebGL code for initializing the tetrahedron points. You may want to skip to the second code block, because you may be able to answer without this.

    //Making a tetrahedron with equal sides
    //Using rotation matrices to determine the points

    //-120 degrees
    var q = -Math.PI/2.0 * 4.0/3.0;
    //Transformation matrix for X-axis rotation
    var rotationArrayX = [
        1.0,    0.0,            0.0,            0.0,
        0.0,    Math.cos(q),    Math.sin(q),    0.0,
        0.0,    -Math.sin(q),   Math.cos(q),    0.0,
        0.0,    0.0,            0.0,            1.0
    ];

    var rotationMatrixX = mat4.create(rotationArrayX);
    var d = vec3.create(new Array(0.0, 1.0, 0.0)); //Topmost point
    var a = vec3.create();
    mat4.multiplyVec3(rotationMatrixX, d, a);

    //Now we have the top most point and the first point of the base
    //After rotating the vector A with 120 degrees two times, we have the 3 base points

    //120 degrees
    q = -q;
    //Transformation matrix for Y-axis rotation
    var rotationArrayY = [
        Math.cos(q), 0.0, -Math.sin(q),     0.0,
        0.0,         1.0,       0.0,        0.0,
        Math.sin(q), 0.0, Math.cos(q),      0.0,
        0.0,         0.0,       0.0,        1.0
    ];

    var rotationMatrixY = mat4.create(rotationArrayY);

    //Calculating points B and C
    var b = vec3.create();
    mat4.multiplyVec3(rotationMatrixY, a, b);
    var c = vec3.create();
    mat4.multiplyVec3(rotationMatrixY, b, c);

    //The remaining point is the top point

    var vertices = new Array();

    //bottom
    vertices.push(a); vertices.push(b); vertices.push(c);
    //front
    vertices.push(b); vertices.push(c); vertices.push(d);
    //right
    vertices.push(c); vertices.push(a); vertices.push(d);
    //left
    vertices.push(a); vertices.push(b); vertices.push(d);

How should I imagine texturing these triangles? Is this a valid set of texture coordinates?

    var textureCoords = [
        //bottom
        0.5, 1.0,
        0.0, 0.0,
        1.0, 0.0,

        //front
        0.5, 1.0,
        0.0, 0.0,
        1.0, 0.0,

        //right
        0.5, 1.0,
        0.0, 0.0,
        1.0, 0.0,

        //left
        0.5, 1.0,
        0.0, 0.0,
        1.0, 0.0,
    ];

I based this on http://www.codeguru.com/forum/showpost.php?p=1542703&postcount=2:

  -------(0.5,1)-------
  |                   |
  |      Texture      |
  |      Image        |
  |                   |
  |                   |
(0,0)---------------(1,0)

Thanks in advance!


texts: how to handle server tick update for multiple rooms? (Nodejs)

texts:
I'm making a multiplayer game using socketio + nodejs. Currently I use setInterval on my server and requestAnimation on my client render. Now I want to create multiple game instances for each room and so I ask how to do so efficiently:

Do I initialize a new setInterval for every game created and call clearInterval when that game ends? or...
Should I create only one instance of setInterval and loop through each active game and update them?
Should I be using setInterval at all?

EDIT: For clarification, my current single setInterval simply does this at about 15hz:

-update each player position based on input

-notify all clients of new positions

input is received as soon as the client sends them, handled by socketio. Sending this many emits is intentional because my server is authoritative and my game is slow (imagine a snakes clone). I intend to allow as many games as there are rooms, which is indefinite (or as many as one server can handle)


texts: How exactly does XNA's SpriteBatch work?

texts:
To be more precise, if I needed to recreate this functionality from scratch in another API (e.g. in OpenGL) what would it need to be capable of doing?

I do have a general idea of some of the steps, such as how it prepares an orthographic projection matrix and creates a quad for each draw call.

I'm not too familiar, however, with the batching process itself. Are all quads stored in the same vertex buffer? Does it need an index buffer? How are different textures handled?

If possible I'd be grateful if you could guide me through the process from when SpriteBatch.Begin() is called until SpriteBatch.End(), at least when using the default Deferred mode.