texts:
I have a camera that I pan around a large image which works fine, however when I reach the end of the image I can keep panning on and on, forver. I have looked everywhere for an answer on how to prevent this but the only one I found did not use panning and I could not get it to work.

My code atm is very simple:

map.setPosition(-map.getWidth()/2, -map.getHeight()/2);

public boolean pan(float x, float y, float deltaX, float deltaY) {
        cam.translate(-deltaX * PAN_SPEED, deltaY * PAN_SPEED);
        cam.update();
        return true;
    }

My Image is very large, 4096x4096, and my camera is 480x800. My problem is I have no idea how to get the distance I have panned, and even if I did I dont know how to stop a pan from moving past a certain point, just setting camera position won't work because then there will be a "bounce" back.

Basically I have a rectangle inside another rectangle, and the inner rectangle should not be allowed to move outside the larger. But as I said I don't really know where to start since I can't get the panning distance.

Ex of something I've tried:

@Override
public boolean touchDown(float x, float y, int pointer, int button) {
    startX = x * PAN_SPEED;
    return false;
}

@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
    if(-totalX > map.getX() + cam.viewportWidth/2){
        cam.translate(-deltaX * PAN_SPEED, deltaY * PAN_SPEED);
        cam.update();
    }
    return true;
}

@Override
public boolean panStop(float x, float y, int pointer, int button) {
    endX = x* PAN_SPEED;
    totalX += endX - startX;
    System.out.println("pan: " + totalX + ", map: " + map.getX());
    return true;
}

This is just a test, basically I can't move anymore after I hit the left border of the image, but totalX still keeps adding up so this will not work.

EDIT: Got it to work, code below:

@Override

public boolean pan(float x, float y, float deltaX, float deltaY) {
        cam.translate(-deltaX, deltaY);
        keepCameraInBounds();
        cam.update();
    return true;
}

private void keepCameraInBounds () {
    OrthographicCamera c = this.cam;
    Vector3 camPos = c.position;
    float HW = c.viewportWidth / 2, HH = c.viewportHeight / 2;
    camPos.x = MathUtils.clamp(camPos.x, map.getWidth()/2 - map.getWidth() + HW, map.getWidth() - map.getWidth()/2 - HW);
    camPos.y = MathUtils.clamp(camPos.y, map.getHeight()/2 - map.getWidth() + HH, map.getHeight() - map.getHeight()/2 - HH);
}


texts: Implementing game state without switch statements everywhere?

texts:
Executive summary

Are there any good tutorials on Game State FSMs, particularly OOP/OOD-based and not switch-statement-based?

Summary

Is there a practical process for creating a game state engine other than using a switch statement, preferably with examples? Wikipedia's event-driven FSM article only shows a switch statement and the article on FSMs is strictly theory-based with no practical examples.

Background

Currently all my games use a very simplistic game state "engine" that uses switch statements everywhere. It's very messy, violates DRY horribly, and does not scale very well.

Each state is treated as a level and must be checked at all three points throughout the game loop, i.e. Input, Processing, and Render. If a level or screen is added it must be added to all the switch statements.

Practical example of recreation of pac-man for educational purposes (seriously, this was a school project a few years ago):

enum STATE {
    LOADING,
    TITLE,
    LEVEL_ONE,
    LEVEL_TWO,
    // ...
    WIN,
    GAME_OVER,
    CREDITS,
}GAME_STATE;

void Input() {
    // ...

    switch(GAME_STATE) {
        case LOADING:
            break;
        case TITLE:
            break;
        case LEVEL_ONE:
        case LEVEL_TWO:
        // ...
            InputCommon();
            break;
        case WIN:
        case GAME_OVER:
            if(keyboard->KeyDown(KEY_ENTER))
                GAME_STATE = CREDITS;
            break;
        case CREDITS:
            if(keyboard->isKeyPressed())
                quit = true;
            break;
    }
}

void Processing(int dead) {

    // ...

    switch(GAME_STATE) {
        case LOADING:
            break;
        case TITLE:
            break;
        case LEVEL_ONE:
        case LEVEL_TWO:
        // ...
            ProcessLevel();
            if(GAME_STATE == LEVEL_SEVEN) {
                // ...
            }
            break;
        case WIN:
            break;
        case GAME_OVER:
            break;
        case CREDITS:
            break;
    }
}

void Render() {
    // ...

    switch(GAME_STATE) {
        case LOADING:
            break;
        case TITLE:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(0));
            break;
        case LEVEL_ONE:
        case LEVEL_TWO:
        // ...

            // ...
            break;
        case WIN:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(3));
            break;
        case GAME_OVER:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(1));
            break;
        case CREDITS:
            sh->Draw(_gw->GetBackBuffer(), sh->Index(2));
            break;
    }

    //End render process, display to screen.
    _gw->EndRender();

}


texts: Grappling hook script sometimes causing jitter

texts:
I am trying to implement a grappling hook mechanic.

My grappling script is attached to my camera that is attached to the player.

Sometimes when I try to grapple onto a wall, it causes jitterting when the grapSpeed variable is 40 or more. When it's more than 40, it happens almost all the time and it's more intense.

My walls' rigidbodies are set to no gravity, kinematic, freeze position and rotation. My player isn't kinematic and has collision set to continuous dynamic.
Here is the grappling script:

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

public class graplin : MonoBehaviour
{
    public GameObject player;
    public GameObject cam;
    public float hookSpeed;
    Vector3 graPos;
    bool canClick = true;

    void FixedUpdate()
    {

        if(Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            if(Physics.Raycast(transform.position,(transform.position - cam.transform.position).normalized,out hit))
            {
                graPos = hit.point;
                canClick = true;
            }
        }

        if(Input.GetMouseButton(0) & canClick)
        {
            player.GetComponent<playerControler>().enabled = false;
            player.GetComponent<Rigidbody>().useGravity = false;

            player.GetComponent<Rigidbody>().velocity = ((graPos - player.transform.position).normalized * hookSpeed);

        }
        if(!Input.GetMouseButton(0))
        {
            canClick = false;
            player.GetComponent<playerControler>().enabled = true;
            player.GetComponent<Rigidbody>().useGravity = true;
        }
        if(Input.GetMouseButtonUp(0))
        {
            player.GetComponent<Rigidbody>().velocity = Vector3.zero;
        }
    }

}

here is the video I took of the problem
the video


texts: Level design / lore writing - how to compel player to go through all locations in a star-shaped level

texts:
I am trying to design a map for souls-like game and stumbled upon such problem:

According to the lore i have a self-contained city that is supposed to be built with convenience in mind.

I am currently designing a graph that represents which locations i have within the city and how they are connected to each other.

For the sake of convenience (for people living in the city) it makes sense for this graph to be somewhat reminiscent of a star (a central square/street and other minor streets flowing from it leading to different locations). Thus it would never take too long to go from point A to point B.

The problem is that with such design player has no obvious reason to go through every single location (which i really want to enforce).

The final goal of the game is to reach certain location on the map (not in the city, the city is just a part of a bigger world) and from player's perspective it makes sense to take the shortest path available.

How could i force the player to go through all the locations without making it obvious that the city was designed just for this and not actually for people to live in it?

In some places i would put doors that only open from one side or require keys from a location that player would otherwise not go through, but using this everywhere quickly gets old and annoying. What else can i do?

I'm fine with altering the city's layout as far as it makes sense in the game's world. Like having a city built like a spiral because it's built on a mountain. But then i need to come up with an idea why would people build the city on a mountain in the first place?

Edit:
originally i did not make it clear that i to make it unavoidable for the player to go through all locations, not just strongly encourage


texts: How to solve this Git SourceTree conflict?

texts:
I have recently joined a amateur studio as the single programmer. The previous programmers have left me the project folder. Upon trying to create a repository and a new remote to have version control I encountered a problem. Upon using source tree a lot of previous versions appeared, on a pretty long branch, somehow it knew all the previous versions and who made them.

Now, upon trying to push them to a new remote I created, as I do not have access to the old one, I get a conflict problem and upon pulling I get another.

git -c diff.mnemonicprefix=false -c core.quotepath=false --no-optional-locks push -v --tags --set-
upstream ********* master:master
Pushing to https://github.com/*******
To https://github.com/******
! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://github.com***'

hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Completed with errors, see above.

f

git -c diff.mnemonicprefix=false -c core.quotepath=false --no-optional-locks fetch ***

git -c diff.mnemonicprefix=false -c core.quotepath=false --no-optional-locks pull --no-commit
****
 master
From https://github.com/********
* branch            master     -> FETCH_HEAD

fatal: refusing to merge unrelated histories
Completed with errors, see above.


texts: How to get a random Vector 2 within a range

texts: I'm working on a game and I need the objects that get spawned to launch within a range of angles, so like in the horrible 2 second paint image seen below, I need to grab a random vector within that range of arrows, and then the ball will go off in that direction. I'm just not sure how to get a vector within a range like that. This is in C# and Unity, the game is 2D. Any ideas?


texts:
I'm trying to write a shader which renders a multitextured geometry wihout rerendering the geometry with each texture.

In my test I'm not using textures, I just convert the texture index to a color (0: red, 1: blue, 2: green). I'm rendering 3 planes with 3 different "texture index" attributes. The vertex shader just passes that float to the fragment shader where I convert it to an integer (and use this interger as an array indexer in the main shader).

So a vertex consists 4 floats (0-2: position, 3: texture index).
Everything is fine until I'm trying to use that "texture index".

Here's the VertexShader:

#version 130
uniform mat4 proj;
uniform mat4 view;
uniform mat4 world;

in vec3 in_position;
in float in_fl;

smooth out float FL;

void main(void)
{
    FL = in_fl;

    gl_Position = proj * view * world * vec4(in_position, 1);
}

FragmentShader:

#version 130

out vec4 out_frag_color;
smooth in float FL;

void main(void)
{
    int i = int(FL);

    if(i == 0)
        out_frag_color = vec4(1,0,0,1);
    else if(i == 1)
        out_frag_color = vec4(0,0,1,1);
    else if(i == 2)
        out_frag_color = vec4(0,1,0,1);
    else
        out_frag_color = vec4(1,1,1,1);
}

And the result (the numbers are the "texture index" of the plane):

Tested on an Intel HD 4000 GPU and an nVidia GTS 250, same result.
As you can see 0 is OK, but 2.0 is sometimes 2 (green), sometimes 1 (blue), why?
If I pass that "i" to a sampler2D array, nothing shows up on the screen, because "i" is out of the array bounds.

The rendering is done using OpenGL 3.0, with a VAO, an ArrayBuffer and an ElementArrayBuffer.

This is how I setup the attrib pointers:

GL.EnableVertexAttribArray(0); //pos
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, true, sizeof(float) * 4, 0);

GL.EnableVertexAttribArray(1); //tetxure index
GL.VertexAttribPointer(1, 1, VertexAttribPointerType.Float, true, sizeof(float) * 4, sizeof(float) * 3);

I've tried using VertexAttribPointerType.Int and int attributes,
Also I've tried setting the "FL" varaible in the vertex shader, with 0, the result is red which is good, but if I use 1 or 2 the result is again a mess.

So what do you think? It's a rounding problem?
Or how should I render the geometry with multiple textures wihout rerendering the geometry with each texture?


texts:
I was thinking of how to implement overriding of behaviors in a component based entity system.  A concrete example, an entity has a heath component that can be damaged, healed, killed etc.  The entity also has an armor component that limits the amount of damage a character receives.

Has anyone implemented behaviors like this in a component based system before?
How did you do it?

If no one has ever done this before why do you think that is.  Is there anything particularly wrong headed about overriding component behaviors?

Below is rough sketch up of how I imagine it would work.  Components in an entity are ordered.  Those at the front get a chance to service an interface first.  I don't detail how that is done, just assume it uses evil dynamic_casts (it doesn't but the end effect is the same without the need for RTTI).

class IHealth
{
public:
   float get_health( void ) const = 0;
   void do_damage( float amount ) = 0;
};

class Health : public Component, public IHealth
{
public:
   void do_damage( float amount )
   {
      m_damage -= amount;
   }
private:
   float m_health;
};

class Armor : public Component, public IHealth
{
public:
   float get_health( void ) const
   {
      return next<IHealth>().get_health();
   }

   void do_damage( float amount )
   {
      next<IHealth>().do_damage( amount / 2 );
  }
};

entity.add( new Health( 100 ) );
entity.add( new Armor() );
assert( entity.get<IHealth>().get_health() == 100 );
entity.get<IHealth>().do_damage( 10 );
assert( entity.get<IHealth>().get_health() == 95 );

Is there anything particularly naive about the way I'm proposing to do this?


texts: Spawning entities in groups on a 2d tile-based map

texts:
I have a 2d game that generates an "infinite" map of tiles based on a "noise" height map. Each time a new "chunk" of 16x16 tiles is loaded, I have code that randomly chooses a "creature" to spawn into the game. Whether or not a creature will spawn on the tile is random, and which creature type is weighted/random.

However, I'd like to take this to the next level and design a creature that can spawn in groups.

I have a few choices:

Spawn additional entities in a random set of surrounding tiles. Multi-chunk groups are impossible unless I write code to base spawns off of what already exists next to it.
Create a new noise/height-map value that I then use to spawn entities with.

There are pros/cons to each, but I'm hoping someone with more experience can suggest which is better, or a third choice.


texts: How to syncronize two animations without delays

texts:
I have one character idle animation running inside a game in a loop, over and over again.
A a certain time I trigger another animation to be played, for the same character.

The second animation won't play immediately, as will be a discontinuity in my character animation. First I wait for the idle animation to finish and then I play my second animation. Now I have a smooth, continuous animation, BUT I have introduced a delay between my action and character animation.

If I play the second animation right away as it is triggered, the character animation won't be continuous and smooth.

I was thinking on breaking the idle animation in small pieces and also to have the same number of second action animations to match the last frame of the idle pieces. This won't solve the delay completely, only will minimize it a bit.

So it's a magic formula of how can I get rid of this delay?

Thanks.


texts: Background generation with sprites in 2D dimension in Unity

texts:
I am making 2D game with Unity. I want to create a procedurally generated background with a bunch of sprites (space background, I have sprites of nebulas and stars). I want some area around the player to be filled with sprites to some extent.

How to make background filling with sprites inside area around player but outside camera visible area?

How to control generation according to players movement for generating in player moving direction only?

How to control the amount of filling sprites while generating?


texts: MonoGame Linux Mouse.SetPosition doesn't work!

texts:
Having a really weird issue, it seems that no matter what I do I cannot get the Mouse to lock to the center of the screen in MonoGame. I triple checked all the possible noob mistakes, and Mouse.SetPosition does get called. Weirder still, setting Game.IsMouseVisible to false does nothing as well.

        public override void Update(GameTime gt)
        {
            _lastmousestate = _mousestate;
            _mousestate = Mouse.GetState();
            if(LockMouse)
                Mouse.SetPosition(100,100);
            Point distance = new Point(_mousestate.X - _lastmousestate.X, _mousestate.Y - _lastmousestate.Y);
            MouseEntity.Position = new Point(MouseEntity.Position.X - distance.X, MouseEntity.Position.Y - distance.Y);
        }

I'm using Linux Mint 64-bit with Cinnamon.


texts: Enemy AI chase twitching left and right to move vertically

texts:
I'm making an enemy follow the player based on his possition and attack if he is within a distance and his last movement (if the enemy last moved to the left, it will attack to the left, etc.). It attacks just fine left and right but not up or down. I tried watching frame by frame to see what happened and discovered that the enemy was twitching left and right to get to the player even if it was above or below him, which is the reason it is recording the last move to the left or right and not attacking top or bottom.

This is the code I use to update the position to where the enemy is going to move (pposX and Y is the player's current position and stillLock the last direction to where the enemy moved)

        xMove = 0;
        yMove = 0;

        if(pposY < y){  //UP
            yMove = -speed;
            stillLock2 = 3;
        }
        if(pposY > y){  //DOWN
            yMove = speed;
            stillLock2 = 4;
        }
        if(pposX < x){  //LEFT
            xMove = -speed;
            stillLock2 = 1;
        }
        if(pposX > x){  //RIGHT
            xMove = speed;
            stillLock2 = 2;

And this is the method I call to create a rectangle with the range of the attack if the cooldown limit is met and hurt the player if it intersects it's collision bounds. (attack is a boolean var indicating enemy is ready to attack)

public void checkAttacks(){
    attack2Timer += System.currentTimeMillis() - lastAttack2Timer;
    lastAttack2Timer = System.currentTimeMillis();
    if(attack2Timer < attack2Cooldown){
        return;
    }

    Rectangle cb = getCollisionBounds(0, 0);
    Rectangle ar2 = new Rectangle();
    int arSize = 50;
    ar2.width = arSize;
    ar2.height = arSize;

    /*
     * Still lock diagram
     * 1 = Left
     * 2 = Right
     * 3 = Up
     * 4 = Down
     */

    //creates collision rectangle

    if(attack && stillLock2 == 3){          //UP
        ar2.x = cb.x + cb.width / 2 - arSize / 2;
        ar2.y = cb.y - arSize;
    }else if(attack && stillLock2 == 4){    //DOWN
        ar2.x = cb.x + cb.width / 2 - arSize / 2;
        ar2.y = cb.y + cb.height;
    }else if(attack && stillLock2 == 1){    //LEFT
        ar2.x = cb.x - arSize;
        ar2.y = cb.y + cb.height / 2 - arSize / 2;
    }else if(attack && stillLock2 == 2){    //RIGHT
        ar2.x = cb.x + cb.width;
        ar2.y = cb.y + cb.height / 2 - arSize / 2;
    }else
        return;

    attack2Timer = 0;

    //if something above happened, check collisions
    if(handler.getWorld().getEntityManager().getPlayer().getCollisionBounds(0, 0).intersects(ar2)){ //damages if player is there
        handler.getWorld().getEntityManager().getPlayer().hurt(1);
        return;
        }
    }

I would appreciate so much if anybody had an idea of how to fix this! (And I'm trully sorry about the code dump).


texts: Load individual sprite from a sprite sheet and make it a FlxSprite

texts:
I'm using flixel and flixer power tools which contains a FlxButtonPlus class that allows me to load 2 FlxSprite as each button state, the problem is that FlxSprite requires a Class a its source but I would like to have a single spritesheet for all my buttons and call each one from there, rather than having a bunch of pngs for every button and every state.

Any idea on how to do that?


texts: Draw circle around gameobject to indicate radius

texts:
I have a tower in my tower defense game im making with an upgradable radius and i would like when the user clicks the tower to show the radius as a circle around the tower

My original thought was to create a cylinder gameobject and place it flat below the tower but when enemies come torwards the tower they "trip" and start spiraling everywhere(yep had a blonde moment)

Then I took the collider off the cylinder but this caused some really wierd things to happen between the ground and the cylinder(major graphical glitches)

So is there anyway for me to draw a circle that is just kinda there as a visual?

The tower is stationary and never moves and the radius of the tower can be accessed through radius

Also the camera is also stationary below is a screenshot of the game view
please disregard it saying "new text" those are set at runtime


texts:
Here's some sample code I copy pasted to try and get a Pyglet layout to work.  I just get a blank screen.  Every time I try to write my own code based on the docs or copy/paste some example code it just will not render the layout.

Interwebs reveal a few other people with this issue but no answers given.

Labels seem to work fine although even they are quirky.

import pyglet

white = (255, 255, 255, 255)

window = pyglet.window.Window(width=200, height=200, caption='Text layout')

# document
document = pyglet.text.decode_text(
    ('Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! '
     'Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!'))
document.set_style(start=0, end=0, attributes=dict(font_size=12, color=white))

# text layout
text_layout = pyglet.text.layout.TextLayout(document=document,
                                            width=window.width,
                                            height=window.height,
                                            multiline=True,
                                            wrap_lines=True)
text_layout.color = (.5,.5,.5,1.0)

@window.event
def on_draw():
    window.clear()
    text_layout.draw()

pyglet.app.run()


texts: I've created a LibGDX project. I imported the build.gradle. The core and desktop modules are imported successfully, but the android not. So I add the content roots. The project compiles, I could build an apk as well via gradle build, but the libgdx android libraries are not imported by the IDE, so classes like com.badlogic.gdx.backends.android.AndroidApplication are unresolved. This wasn't a problem so far, because it compiles, but now I'd like to develop Android specific code, so the code completion would be great. Any ideas how I could add the relevant dependencies from the build.gradle?


texts: Recommended 2D Game Engine for prototyping

texts:
What high-level game engine would you recommend to develop a 2D game prototype on windows? (or mac/linux if you wish)

The kind of things I mean by "high-level" includes (but is definitely not limited to):

not having to manage low-level stuff like screen buffers, graphics contexts
having an API to draw geometric shapes
well, I was going to omit it but I guess being based on an actual "high-level" language is a plus (automatic resource management and the existence a reasonable set of data structures in the standard library come to mind).

It seems to me that Flash is the proverbial elephant in the room for this query but I'd very much like to see different answers based on all kinds of languages or SDKs.


texts: How to write a script for circular motion?

texts: Сan any body explain me the script for the tangential motion,so that when i cut the rope circle should move tangentially:


texts: Why isn't my sprite being drawn in the correct position in XNA?

texts:
Sorry if this has been asked before, but I can't seem to find it here. I'm trying to make an asteroids clone in XNA. I took the Game State Management project and am making new classes for things like the player and placing them in the GameplayScreen class. For some reason my ship isn't being draw correctly.

GameplayScreen's Draw method:

 public override void Draw(GameTime gameTime)
    {
        ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                           Color.CornflowerBlue, 0, 0);

        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

        spriteBatch.Begin();
        //draw fps
        if(showFPS)
            spriteBatch.DrawString(framerateFont, "FPS: " + frameRate, new Vector2(15, 15), Color.White);

        player.Draw(spriteBatch);

        spriteBatch.End();

        // If the game is transitioning on or off, fade it out to black.
        if (TransitionPosition > 0 || pauseAlpha > 0)
        {
            float alpha = MathHelper.Lerp(1f - TransitionAlpha, 1f, pauseAlpha / 2);

            ScreenManager.FadeBackBufferToBlack(alpha);
        }
    }

And my ship's drawing code:

 public PlayerShip(Game game)
    {
        this.game = game;
        Viewport view = game.GraphicsDevice.Viewport;
        center = new Vector2(view.Width / 2, view.Height /2);
        sourceRectangle = new Rectangle();
        Reset(center);
    }

    public void Reset(Vector2 position)
    {
        this.position = position;
    }

    public void LoadContent()
    {
        ship = game.Content.Load<Texture2D>("ship");
        sourceRectangle = new Rectangle(0, 0, ship.Width,
            ship.Height);
        origin = new Vector2(ship.Width / 2, ship.Height);
    }

    public void Update(GameTime gameTime)
    {
        HandleInput();

    }

    //handles all keyboard input by user. rotates ship based on current rotation.
    private void HandleInput()
    {
        input = Keyboard.GetState();
        float x = position.X;
        float y = position.Y;
        Matrix m = Matrix.CreateRotationZ(rotation);

        if (input.IsKeyDown(Keys.Right))
            rotation += turnFactor;
        else if (input.IsKeyDown(Keys.Left))
            rotation -= turnFactor;
        else if (input.IsKeyDown(Keys.Up))
        {
            x += m.M12 * directionFactor;
            y -= m.M11 * directionFactor;
        }
        else if (input.IsKeyDown(Keys.Down))
        {
            x -= m.M12 * directionFactor;
            y += m.M11 * directionFactor;
        }
        position.X = x;
        position.Y = y;
        Console.WriteLine("Y: {0} ", y);
        Console.WriteLine("X: {0} ", x);
    }

    public void Draw(SpriteBatch sb)
    {
        Vector2 origin = new Vector2(ship.Width / 2, ship.Height);
        sb.Draw(ship, ship.Bounds, null, Color.White, rotation, origin, SpriteEffects.None, 0f);
    }

I hooked the project up to a console window and it seems that the X and Y positions are updating correctly code wise, but not visually. It seems to update where it is rotationally, but going up or down doesn't draw correctly.

Image of what it's doing http://imgur.com/4cKBk


texts: How to make an object fly out of a slingshot?

texts:
At the moment I'm improvising a slingshot, the user can click and drag the projectile and let go.
The force on the object is calculated by getting the distance between the vector of the slingshots two forks and the vector between where the user pulled it.
However this will always result in a positive number and will not take into account the angle of the object relative to that of the slingshot. How can I make it fly out of the slingshot correctly?

My attempt:

float distance = mousePos.dst(pouchPos.x, pouchPos.y, 0);
Vector2 d = new Vector2(pouchPos.x - mousePos.x, pouchPos.y - mousePos.y);
object.setVelocity(d.nor().x * FIRE_SPEED, d.nor().y * FIRE_SPEED);


texts: Touch pad controls not working in apk, working from Unity Remote

texts:
I've come across something unusual with my HTC One M8, I'm not sure if it's phone specific, a bug in unity, or just poor setup on my part.

I've been using Unity Remote 4 to test in realtime, and it's really quite awesome. Don't think I've ever seen something quite so efficient for testing short of .NET and Windows Phone (and even then it's bloody close!)

Anywho, when in Unity Remote, obviously it's not an APK that's running but something that's running in some sort of virtual machine style environment, whereby the code is executed directly with massive links via USB. I tried, yesterday, to install my application as an apk, and for some reason the on screen controls didn't work. The boxes for them didn't appear (there is a dashed line around each control "area", and tapping and swiping simply did nothing.

I'm curious if this is because I've set the controls up as a "debug only" option, so I tried a debug build and still nothing. I tried a few other things like checking all the settings I could find to ensure nothing suggested that they were debug only, with no luck. Not sure where to turn.

If it helps at all, I'm using the "sample pack" (from the default assets) for mobile development, with a sprite as my "player", configured as a 2d sprite in a 2d side scroller game. I'm about to try it with the absolute default settings, literally just as a test, but I'm pretty confident that it won't make a blind difference.


texts:
I am using a shader that uses a gradient noise node and time to add a wavy effect to a grid like texture. The issue with doing this is that it causes the lines to be misaligned on the different faces of the cubes.

What I would like is for the lines to be conjoined, like this (wavy effect not applied)

The shader graph layout I am using to generate this effect is

How can I go about fixing this issue so that all the lines are conjoined, but also have a wavy effect over time?

Edit

A rough sketch of what I am after. Here the black dots represent the physical shape of the object and the lines should be able to wave around the whole object and all be connected, regardless of whether there is an edge there or not.


texts: Why are not the images loaded in Phaser?

texts:
I am starting to use phaser to create games and I found a problem that I can not find for more tests that I did.
I can not show the images I am uploading. You only see a small square in the center, (I show it in this capture: when you should see the entire background of the canvas in green, which is the image that first charge.
In the example I only charge one, so that more if it does not work.
I do not see what error I'm committing, because the navigator inspector does not show errors.
The server is created with Node.js.

const http = require('http')
const fs = require('fs')

const server = http.createServer((req, res) => {
    fs.readFile("./part1.html", (err, data) => {
        if(err){console.error(err); return;}
        res.end(data)
    })
})
console.log('escuchando en el puerto 3000')
server.listen(3000)

I show the code for if someone can see the error that I am committing.
Thank you.

I EDIT the question:

I add the code that I should add first.
The project is in a folder called Game.
Here is the file server.js and package.json
There is also a folder called public where the html code and images are located.
I show you the code.

<!doctype html>
<html lang="es">

<head>
 <meta charset="UTF-8" />
 <title>Primer juego en Phaser</title>
 <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
 <style type="text/css">
  body {
   margin: 0;
  }
 </style>
</head>
<body>
 <script type="text/javascript">

  var config = {
   type: Phaser.AUTO,
   width: 800,
   height: 600,
   scene: {
    preload: preload,
    create: create,
    update: update
   }
  };

  var game = new Phaser.Game(config);

  function preload() {
   this.load.image('sky', 'sky.png')
   this.load.image('sky', 'assets/sky.png');
         this.load.image('ground', 'assets/platform.png');
         this.load.image('star', 'assets/star.png');
         this.load.image('bomb', 'assets/bomb.png');
         this.load.spritesheet('dude', 'assets/dude.png', {         frameWidth: 32, frameHeight: 48 });

  }

  function create() {
   this.add.image(400, 300, 'sky')
  }

  function update() {
  }

 </script>
</body>
</html>


texts: Unity Rigidbody2D to act on certain gameobject only

texts: I am creating a 2D game and the player object has a rigidbody2D attached to it. The game works fine until the player collides with a power up. The rigidbody physics get all messed up. So I was wondering is there a way so that rigidbody will only act on enemies and be disabled for power ups?


texts: Will using OpenGL for rendering with SDL make my 2D game run smoother?

texts: I've been working on a 2D game using SDL.  I've noticed the objects look blurry and glitchy when they're moving, so I was thinking about using OpenGL to render the graphics.  Would this help?  What are the pros and cons of using OpenGL for a 2D game?


texts:
Okay so i havebeen rotating my enemy to face the player using

float targetrotation = Math.Atan2(playerpos-enemypos);
enemy.rotation = targetrotation; (<this line of code i want to change)

This simple method has worked fine so far for getting the enemy to look at the player's position. However i decided to add some extra code to get the enemy to gradually rotate towards the player using this method:

if(enemy.rotation < targetrotation)
{
   enemy.rotation++;
}

if(enemy.rotation > targetrotation)
{
   enemy.rotation--;
}

Now the problem i am having is that when the player moves for example from 360 degree target to 1 degree then the enemy rotates the long way round to move to the 1 degree instead of simply adding 1 degree. Any help on how to correct this problem would be welcomed. I have a picture below:


texts: Unity, Detect the last GameObject in the hierarchy of a given list of GameObjects

texts:
I have a list of GameObject , and I need to know which one is the last in the hierarchy ( This is for a UI system, So is kind of 'which one is showing up')

I have a cursor managed by GamePad , and I use Raycast to see if he clicked something, It give me an array of Gameobjects but I need to know which one is showing up(on top of the others) to click on it

Example this is my full hierarchy:

GameObject A
        GameObject B
        GameObject C
GameObject D
        GameObject E
        GameObject F
GameObject G
          GameObject H
               GameObject I
           GameObject J

The list of raycast contain 'GameObject D','GameObject A','GameObject I'

How I cand find that 'GameObject I' is the last one? they don't have a common root


texts:
I have a script that is made to run when the game is loading.
That script set the resolutions, fullscreen, and loads other screen and important settings and it applies them.
I have the script attached to a gameObject in the main screen that have some game and scene scripts.
The problem is that everytime that you return to the main scene, that script runs again and cause several bugs.
So, there is a way to run a script only at game startup?


texts: 2D Sprite batching in OpenGL: How to send transformation data to GPU

texts:
OpenGL newbie here.

So I'm trying to implement sprite batching to draw ~100 sprites per draw call. I've created a VBO that contains texture coordinates, vertex coordinates, color data (for tinting), and a mat4 matrix for transforms.

So far, so good, right? Well, everything is working but the transform portion of my VBO. My theory is that I could push a mat4 with all of the rotation, scaling, flipping, and world location data applied to it, so that it gets multiplied in with viewports (see glsl code below).

#version 130

//Vertex position attribute
in vec2 vertexPos;

//Texture coordinate attribute
in vec2 texCoordIn;
out vec2 texCoord;

// Vertex color
in vec4 textureColorIn;
out vec4 textureColor;

// Matrix transformations for the sprite
in mat4 transformation;

void main()
{
    //Process texCoord
    texCoord = texCoordIn;

    // Process texture color
    textureColor = textureColorIn;

    //Process vertex
    gl_Position =  gl_ProjectionMatrix * gl_ModelViewMatrix * vec4( vertexPos.x, vertexPos.y, 0.0, 1.0 ) * transformation;
}

So here's my question, if you were to send transform data to the GPU, how would you do it? Sending a mat4 over the wire per vertex seems like overkill.


texts: Enlarge screen space Texture by set pixel amount

texts:
I have a texture shown over the screen using screen space UV's. The Texture is 495x,596x, Screen size is 888,500, but can change. The Texture has a Tile of (3.469775f,1.392644f) to correct for distortion from being stretched to the Screen's size, and has repeat set to Clamped. So basically, I'm showing a Texture of an arbitrary size on screen and using Tile and Offset in the shader to correct for distortion and keep the texture at its original aspect ratio.

Now my problem is I want to Zoom in and out by a set pixel amount in Screen space.
So lets say: I need the texture to increase in width by 10 pixels in screen space.
What is a formula I can use to recalculate the Tile and Offset so that the texture stays at the same aspect it was but increases by the amount I want it zoomed?

I've been trying things like: 1 Pixel = (1f / Camera.main.pixelWidth).
So to zoom by 10 pixels I would go something like Tile.x += (10f * (1f / Camera.main.pixelWidth));
But this doesn't seem quite right, I'm not seeing it increase the Texture by the right number of pixels...

My current function is something like this, but for Zoom = 5f, it's only enlarging by about 2px. AspectRatio = Tiling in the Material and WidthOffset/HeightOffset is just the Offset.

public void ZoomOverlay(float ZoomAmount)
{
    AspectRatio.x -= ZoomAmount * (AspectRatio.x / (float)Camera.main.pixelWidth);
    AspectRatio.y -= (ZoomAmount * (AspectRatio.x / (float)Camera.main.pixelHeight)) / 2f;

    WidthOffset += ((ZoomAmount / 2f) * (AspectRatio.x / (float)Camera.main.pixelWidth));
    HeightOffset += ((ZoomAmount * (AspectRatio.x / (float)Camera.main.pixelWidth)) / 2f) / AspectRatio.x;
}


texts: Unity: Why does playModeStateChanged get called after Start?

texts:
I have this:

[InitializeOnLoad]
public class MyClass
{
    static MyClass()
    {
        EditorApplication.playModeStateChanged += x => { PlaymodeStateChanged(); };
    }

    private static void PlaymodeStateChanged()
    {
        Debug.Log("Play mode changed");
    }
}

and another class with a Debug.Log("Start()"); in the Start method.
When I hit play I see on the log output:
Start()
Play mode changed

Shouldn't playModeStateChanged get called before Start is called on all objects? Any way to go around this? I need this so I can initialize an object before other objects that need to reference this one run Start.

Thanks in advance!


texts: Position problems instantiating lasers at the sides of a space ship

texts:
I'm developing a demo of a 3D Space Ship game concept in Unity, just for learning purposes.

I have a cube representing my space ship in the scene, and a laser prefab that is instantiated at the 2 sides of the space ship any time the user presses the spacebar, i use this C# code (placed in the script attached to the space ship, just a cube right now) to calculate the position of the lasers and instantiate them:

Vector3 laser1Position =
    this.transform.position + this.transform.forward + this.transform.right;
Vector3 laser2Position =
    this.transform.position + this.transform.forward - this.transform.right;

Instantiate (laser, laser1Position, this.transform.rotation);
Instantiate (laser, laser2Position, this.transform.rotation);

At this point, everything worked perfect, and the lasers are instantiated correctly at the sides of the cube, exactly at the middle of the 2 sides.

The problem came yesterday, when i replaced the cube by a real space ship model, a simple design made by my brother in Blender, and attached the same script my cube had, the lasers are instantiated very above from the space ship, producing the effect seen in the next image, the lasers are spawned at the red line i drew just for showing purposes, when i need them to be instantiated at the green line:

Here you can see the space ship model vs the cube, both firing lasers:

We designed the space ship model in blender, in the origin of coordinates, without any other objects or light sources, so my doubts are:

Why are the lasers spawned that high if the model is not there? Is really the model bigger than i see in the editor? (The green box is a box collider i added for collisions managing)

Should we configure or touch something in the Blender project to stablish the real size or axis of the model when we import it?
Is there a better method of calculate where the lasers should be spawned that this one i am using? Imagine that i want to spawn them in the point of the wings, in front of them. Is there any marker or method i could use to easily spot the place where the lasers should be spawned at runtime? Instead of manual calculating it or by test-error.

I don't have the model here right now, if you need it please let me know and i will try to upload it to somewhere later.

Thank you so much for your help!


texts: 3D OBB vs OBB Collision Detection and Response

texts:
(Edited, was a rather goofy, long question. I have since decided on using JBullet and I love it.)

How can I accomplish 3D OBB vs OBB collision detection in my game? I understand how AABB's detect being inside one another, and I understand how to rotate a point around another point. But once a collision is detected, how should a physics engine respond to that? It is the collision and resolution that I don't understand how to do; making the objects move/react appropriately.


texts: Unity Event after Layout update but before OnWillRenderObject()

texts:
Looking for subscribe-able event that occurs right after Layout update in Unity but before OnWillRenderObject is called.

Working solution is Canvas.willRenderCanvases, but useful to know if more events exist before or after this event:
http://docs.unity3d.com/ScriptReference/Canvas-willRenderCanvases.html

Here is picture in-case unfamiliar with Unity Layout update:


texts:
I'm just starting with physics, so I'm not always sure about what I'm doing. It's a 2D project but I'm using 3D physical objects like SphereCollider etc..

What I have:

Objects floating in space and affecting each other through gravity:

protected virtual IEnumerator OnTriggerStay(Collider other) {
    yield return new WaitForFixedUpdate();

    if(other.attachedRigidbody) {
        Vector3 offsetVector = this.transform.position - other.transform.position;
        float distance = offsetVector.magnitude;
        float gravityForce = (other.rigidbody.mass * mass) / Mathf.Pow(distance, 2);
        // Clamp gravity.
        if(gravityForce > 1.0F) {
            gravityForce = 1.0F;
        }
        other.attachedRigidbody.constantForce.force = offsetVector.normalized * gravityForce;
    }
}

There are controllable objects on which the player can click and drag a line away from the object in order to give it a force (shoot) in the opposite direction.

What I want to achieve:

The player should see a rough prediction of the way while aiming. That means that the way-prediction needs to take in account the current velocity, the force which would be applied when the player release the mouse button and the gravity of the surrounding objects.

What I have tried so far:

For testing purposes I just save the computed/predicted positions in an array and draw those positions in OnDrawGizmos().

I wrote a method which returns the gravity influence for a certain position called computeGravityForPosition(Vector3 position).

And thats how I try to calculate the positions:

private void drawWayPrediction() {
    Vector3 pos = this.transform.position;
    // The offsetVector for the shooting action.
    Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition);
    forceVector.z = 0.0F;

    // The predicted momentum scaled up to increase the strength.
    Vector3 force = (forceVector.normalized * forceVector.magnitude);

    // 1. I guess that this is wrong, but don't know how to do it properly.
    momentum = this.rigidbody.velocity + force;

    for(int i = 0; i < predictionPoints.Length; i++) {
        float t = i * Time.fixedDeltaTime;
        momentum += computeGravityForPosition(pos);
        pos += momentum * t * t;
        predictionPoints[i] = pos;
    }
}

At the beginning, when the objects just slowly approaching each other it looks okay. After the first shot, the prediction is completely wrong. I guess it is because of 1. in the code. Just adding the force to the velocity is probably horrible wrong.

Thank you very much for your time.

EDIT:

I removed seemingly unnessecary parts.

I still think that the main problem lays in 1. in the code. I just don't know how to mix up the current movement of the object (from which I only have the current velocity as far as I know the physics engine of unity) with the new created force:

Vector3 forceVector = pos - Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 force = (forceVector.normalized * forceVector.magnitude);


texts: Dr.Strange's door in Unity3D, how to put a projected void on a plane?

texts:
My question is about a visual trick I would like to perform in Unity3D. I want the player to walk outside a door and see no walls of the room behind them, just the door. They should still be able to see inside the room as if it were a "projected box plane" but not the walls containing it. They won't be able to touch where the walls should be, so I'm not worried about any invisible walls.

I'm imagining it would be similar to a "projected box plane" but I couldn't find any resources on how to do that in Unity3D. Just point me in an area I could research if this problem is more complicated then I thought.

Thank you.


texts: What is the Unity 2019.3.5 version of `UnityEngine.UI.Text`?

texts:
I was following a tutorial on how to create a dialogue Box in Unity, and in one part of the tutorial the tutor imports UnityEngine.UI and creates an object of type Text, but my version of Unity is 2019.3.5f1 and I learned through searching a bit online that this UnityEngine.UI doesn't exist anymore in this version, and that it was replaced with
UnityEngine.UIElements, and this Text type doesn't exist anymore as well.
I couldn't find a replacement for Text or what is the new nomenclature, nothing from trying stuff that popped in the auto complete or searching for answers in the Internet gave me answers. Maybe I just searched poorly, but if anyone happens to know, could you kindly answer?


texts: How to match font size with screen resolution?

texts:
So I'm working on a game using LibGDX, and I have a problem.

To make my game fit most resolutions, I created a base asset for each aspect ratio, for example, a main menu background image, I made it in 800X600 for 4:3, 1280X720 for 16:9 etc.

Now I am trying to incorporate TextButtons into the game, for the options; My problem is that I can't figure out which font sizes match with which screen resolutions. Is there a way to figure this out, or do I have to go one by one through each of the resolutions I have and just manually match the text to the resolution?


texts: game server/client user input/event handling

texts:
I'm currently getting my feet wet in the realm of networking, so I set a goal to make a simple client/server game using SFML for both graphics and networking. In my head it seemed easy at first, but the more I got into it the more questions arised. I didn't want to make a post before I hadn't done any research, but now, having read many blog posts and articles, there's nothing to lose.

The game I'm working on is a trivial PONG game: server waits for 2 players, when they are connected, clients send server paddle's X position only if mouse is moved. Server reads in the X pos. and sends each client opponent's position.

The problematic part is opponent's behaviour on the client side. When playing both clients + server on my computer, using 100% CPU speed server side, the opponent moves smooth, but having CPU running as fast as it can is nonsense! If I reduce update speed the movement becomes weird so to say.

Might there be anything to do with client-side prediction (I read about it too, but didn't quite grasp how it would be implemented)?
Since there are frequent position changes, should the server's update speed be as high as possible?
I'm using TCP, which I understand is "reliable" = no lost packets. For such fast-paced game like PONG, which protocol is more suitable.

Now, I do not fully understand the magic behind it all, very very thrilled about network programming. I've never been more excited during programming as I am dealing with networking.

Thank you for your attention!


texts: How to prevent the player from calling the Jump function if no collision is detected?

texts:
I am back once again. This time with a basic 2D platformer game. I would like to allow my player to jump but only if the ground bool checks as true. I would like to fix my script so that upon collision with the ground the player is able to jump, but while the player is in the air the player is not able to jump. My platform has a box collider and my player has a collider as well as a rigidbody. How do I go about fixing my script to allow this system to go into effect? Please and Thank you!

public class MovePlayer : MonoBehaviour {

    public float speed = 0f;
    public float height = 0f;
    public GameObject player;

    private bool grounded = false;

    void OnCollisionEnter2D(Collision2D coll)
    {
        if (coll.gameObject.tag == "ground")
            grounded = true;
            return;
    }
    // Use this for initialization
    void Movement ()
    {
        if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.Translate(Vector3.right * speed * Time.deltaTime);
        }

        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Translate (Vector3.left * speed * Time.deltaTime);
        }

        while (grounded = true)
        {
             Jump();
        }
    }

    void Jump()
    {
        if (Input.GetKeyDown (KeyCode.UpArrow) || Input.GetKey (KeyCode.Space)) {
            transform.Translate (Vector3.up * height * Time.deltaTime);
            return;
        }
    }

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

        Movement ();
    }
}


texts:
i hope you can help me. I'm currently stuck at the creation process for projection matrices used by shadow maps.

The problem is the following:
I got the spot/directional light projectionmatrix/boundingfrustum and additionally the bounding frustum of the camera projection matrix.

What i need is the minimal bounding box of these two frustums. How do i get that? Or is there a better way to create projection matrices for shadow maps?


texts: How to form a concave shape out of convex shapes?

texts:
I'm trying to get around the rule of only being able to form convex shapes in the SFML C++ library.

  To do this I'm planning on testing given vertices, and if concave,
  splitting the vertices into groups, testing each groups' concaveness,
  and repeating until a full set of convex shapes results that look
  just like the original shape when put together

What I would like to know is...

What the equation for testing a shapes concaveness is: what is it and how does it work?
How would I split up the vertices of the concave shape so in the end the shape is formed out of as few convex shapes as possible?
Whats the best practice for achieving my goal?

Thanks!


texts: How to set HUD elements position and size depending of resolution

texts: How can I set HUD elements' position and size when changing resolution and maintain the desired layout? All HUD elements (including menu items such as play button, setting button etc) need to get some scaling.


texts: Keeping Aspect Screen Ratio While Stays in Center

texts:
I sqw and I tried this suggestion on *PISTACHIO BRAINSTORMIN** on how to make a good and adaptive screen ration. For every different screen size, let's say I put the perfect circle as a Texture in LibGDX and played it on screen. Here's the blueberry image example and it's perfectly rounded:

When I played it on the Google Nexus 7, the circle turn into a slightly oblonng shape, resembling as it was being flatten a bit. Please observe this snapshot below and you can see the blueberry is almost but slightly not perfectly rounded:

Now, when I tried the suggested code for aspect ratio, the perfect circle retained but another problem is occured. The problem is that I expecting for a view on center but instead it's been moved to the right offset leaving with a half black screen. This would be look like this:

Here is my code using the suggested screen aspect ratio code:

Class' Field

// Ingredients Needed for Screen Aspect Ratio
private static final int VIRTUAL_WIDTH = 720;
private static final int VIRTUAL_HEIGHT = 1280;
private static final float ASPECT_RATIO = ((float) VIRTUAL_WIDTH)/((float) VIRTUAL_HEIGHT);
private Camera Mother_Camera;
private Rectangle Viewport;

render()

    // Camera updating...
    Mother_Camera.update();
    Mother_Camera.apply(Gdx.gl10);

    // Reseting viewport...
    Gdx.gl.glViewport((int) Viewport.x, (int) Viewport.y, (int) Viewport.width, (int) Viewport.height);

    // Clear previous frame.
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

show()

        Mother_Camera = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);

Was this code useful for screen aspect ratio-proportion fixing or it is statically dependent on actual device's width and height?

**see http://blog.acamara.es/2012/02/05/keep-screen-aspect-ratio-with-different-resolutions-using-libgdx/#comment-317*


texts: What are the benefits or drawbacks of splitting the player animation system from the wall collision system into multiple objects pinned to each other?

texts: I'm currently making a simple platformer in GameMaker Studio 2 and I've had people telling me that I need to separate the two things into an invisible wall collider mover and animation sprites pinned on top of it. I've also had people telling me that's overcomplicated and stupid. But I've never heard the reasons why I would or should do it either way.


texts:
I am programming a simple pool game in XNA. I am using Farseer for simple 2d physics but I want to use 3d graphics. My problem is I can't get the rendering to work.

I have one model for the ball and one for the table, both exported from Cinema 4D into .fbx. I am able to load them and even display them, but not on the correct position. Farseer is using standart coordinate system (X+ to the right, Y+ down) and I need to somehow convert the position from farseer and display the models on the right place on the screen and with the correct size (this should be easy to achieve using scale matrix).

I need help finding what my projection, view, and world matrices I should use?


texts: Changing the current state of an entity in the middle of an update step or wait for the end?

texts:
Let's say that I use a behaviour component that holds a function call to be called every update step assigned to an entity. Inside that function call I'm changing the active state for the entity to activated or deactivated, something like this:

void fun_update() {
 this_entity->set_active(true);
 if (this_entity->is_active()) { // This should return true or false?
  ....
 }
}

What would be more correct? To change the state for the current update iteration or wait for the end of the current update step to update the state of the entities?

I know that, unity3d for example, changes the current state, but when coding my own engine I find easier to update it at the end.


texts: SIGSEGV error when returning a new object

texts:
I am attempting a minecraft clone, and I have spent the past 3 hours debugging a SIGSEGV error. I've traced it to returning a new object. return Block(BlockID::Air) for example. When I run my debugging tool, it leads to move.h:

...
 // concept requirements
  __glibcxx_function_requires(_SGIAssignableConcept<_Tp>)

  _Tp __tmp = _GLIBCXX_MOVE(__a);
  __a = _GLIBCXX_MOVE(__b);
  __b = _GLIBCXX_MOVE(__tmp);
}
...

I also get the error whenever I create a new glm::vec3


texts:
Hey all I have a quick question.

I am new and obviously still learning the basics of programming/scripting. However I am confused by the result of a simple script.

The goal is to have a Start Menu with a 3d background.The camera is attached to an Empty Object, which has a script that is meant to constantly rotate.

My confusion, is whether I am live testing in Unity, or a built executable. When the empty object is rotating, it will have a pause or a few milliseconds, and then continue with its rotation. Almost like a planned micro stutter. Regardless of where it is in its cycle. How can I make the rotation as perfectly smooth as possible?

Below is the script for rotating the empty object that the camera is attached to.

public class cameraAnchor : MonoBehaviour {

public float speed = 5f;

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

    //rotate camera anchor around y axis
    transform.Rotate(Vector3.down, speed * Time.deltaTime);
}

}


texts: Quaternion based camera pitch freaking out, and Z-axis drift

texts:
This is the code I use to control my (first person) camera's movement and
rotation. Translation successfully keeps orientation in mind, so that up and
left and such are always in the expected directions, and 'mouselook' controlling
rotation around the Y (yaw) and X (pitch) axes starts out working fine as well.

My problems are two-fold;

First, rotating around the Y and X axes slowly builds up rotational drift around
the Z axis. Now what I think I need to do to correct this is to keep track of an
additional 'up' vector, and to rotate the quaternion so that the camera's up
direction always coincides with this up vector (which would only change when
intended, instead of by drift). But I have no idea how to go about doing this.

The second problem is more clearly a bug. When rotating around the Y (yaw) axis,
the rotation around the X (pitch) axis starts to freak out. At Y 180 degrees, the
up and down motion of the camera's pitching are precisely inverted. And at 90
degree Y angles from the starting orientation, it's as if pitch has become roll
instead, rotating around the Z axis.

So, how do I 'roll up', and what's going on with the pitching?

glm::quat mOrientationQuaternion;
glm::vec3 mPositionVector;
glm::mat4 mViewMatrix;

/*
 *  Takes a translation value for each axis, turns it into a vector, then
 *  rotates that vector by the current orientation in the quaternion, before
 *  adding the result to the position vector.
 */
void Camera::translate(float x, float y, float z)
{
    glm::vec3 translation(x, y, z);
    translation = translation * mOrientationQuaternion;
    mPositionVector += translation;
}

/*
 *  Takes three angles in degrees, and creates a quaternion via an
 *  intermediate vector to represent their rotations. Then the orientation
 *  quaternion is multiplied by this new rotation quaternion to get the new
 *  orientation.
 */
void Camera::rotate(float x, float y, float z)
{
    glm::vec3 angles(glm::radians(-x), glm::radians(y), glm::radians(z));
    glm::quat rotation(angles);
    mOrientationQuaternion = glm::normalize(mOrientationQuaternion * rotation);
}

/*
 *  Creates the view matrix from the orientation quaternion, then translates
 *  it by the position vector.
 */
void Camera::buildViewMatrix()
{
    mViewMatrix = glm::mat4_cast(mOrientationQuaternion);
    mViewMatrix = glm::translate(mViewMatrix, mPositionVector);
}


texts:
I'm an independent game developer considering working with a publisher.  This question is very informative however I have more questions.  Please give feedback on the following issues... I think this can be helpful to many indie devs in the same situation.

Source code: is it common for developers to give the publisher the source code?
Code quality:  does this matter when working with a publisher any more so than when just working on your own (or in a small team)?  Just wondering if developers working for the publisher might scoff at the code quality and perhaps influence the relationship between developer and publisher.
Unique game concepts: are publishers generally biased towards new/novel game concepts?
Intellectual property: if I send a playable demo to a publisher what's to stop them from just reproducing the new/novel game mechanic?  I think the answer is basically nothing... but I'm wondering if this is a realistic concern.
Revenue sharing: how does it work? what's a common ratio?  70/30?  30/70?
Flaky publishers: how common is it for a publisher to "string along" developers for a while then just drop them?  Can this be reconciled with a contract of some kind?

And any other issues you've encountered or heard of.


texts: Unity - soft blur effect for dark void edges

texts:
I'm a former Flash dev working in Unity (or in 3D for that matter) for the first time.

For the game I'm working on, I've designed an interior room like so:

To represent void/space outside the bounds of the current room, there's just black.
In order to hide the back faces of the exterior facing walls, I've created a snug fitting mesh cutout which sits just below the lip of the wall.
If I moved the camera below the surface, you would clearly see that.

I'm quite new to Unity, and have very little experience with shaders.

Anyway, I figured this would be a good place to try for creating my first shader, but I'll need some help.

I'd like to blur/soften the edges where the wall lip meets the void, like so:

The only way I could achieve this effect would be by hacky means, like by using a gradient texture (#00000000 -> #FF000000) UVed around the edges of the wall lips, but I suspect there is a more elegant solution by rendering the black surface with a shader.

Currently, even with a basic understanding of fragment shaders and the rendering process, I would have no idea where to start if I tried to write my own. When I read shader script I can only stare in wonder at the sheer etherealness of it. I just don't know how to craft a solution in such basic terms, but I'd love to learn.

I understand the answer is probably as simple as 'use a gaussian blur', but i would appreciate some more input to steer me on the right path, and maybe some examples to help me understand.


texts: Where to hire a scenario writer for a small interactive story game?

texts:
I need a scenario for a small dialog-based game / interactive story. The game would be used as an example to be shipped with a middleware tool we're developing.

I would like to buy an existing story (it should be dynamic of course — with branching dialogs etc.), or hire someone to write a new one.

Please advise, where to go to find such person / service? We're based in Russia, so getting a talented enough native English writer locally is a bit of a problem.

Update: To be extra clear: We must get all necessary rights to reuse the story and make a derived work (i.e. the game we're talking about) from it. This is a commercial product. Borrowing someone else's work at random and using it just not going to work.

WARNING: Please do not post "I can do it" answers here. This is not a job board! You will get downvoted and your answer will be deleted. If you really want to contact me, look into my profile.


texts: Why use random numbers when it comes to rewards and stats?

texts:
Many games use random numbers for things like attack damage, gold loot, or monster type being spawned. It is obvious that random numbers allow you to generate content to make games more re-playable, but I am talking about specific things. For example: In DOTA, when you kill a monster you get a random amount of gold in between x and y where x and y never change. When you attack anything you have a chance to do damage within a range such as 52-60. How would making the gold drops static change the game?

I feel like the random numbers enhance the game-play, but I am having trouble understanding why. Does anyone know any reasons why random numbers can make game-play better when used with things like damage or loot? I'm hoping for answers that don't attribute it to luck being a good thing.


texts: Unity3d not allowing endpoint to save cookies

texts:
So I'm using an external DLL with Unity to login to a web service and access functions from it.

The DLL works perfectly fine in a command prompt project, but when run in Unity I can log in successfully, but when I try to use any commands I get a session has expired error.

The DLL stores session cookies in the endpoint, so it appears that Unity isn't allowing this custom endpoint to store cookies.

Does anyone know how to make Unity allow custom endpoints to store cookies? Or where in an endpoint I could parse the cookie from so I could feed it in with any service commands?

For reference, here's a link to the main DLL, and here's a link to ContentService. The main DLL is compiled for .NET 3.5 so as to work with Unity.

Just as a reference, here's the exact error code I'm getting in Unity:

FaultException: Your session has expired.
System.ServiceModel.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters)
System.ServiceModel.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters)
System.ServiceModel.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters)


texts: how to move a 2d shape in opengl 4.6 (glfw)

texts:
Class Button
So  from my understanding in order to move a 2d shape you need manipulate the vertices and then update????
If i do need to update the buffer how i would go by doing that?
float xpos = 150 //Cords relative to the window application so let say the window size 480 by 260
float ypos = 60 Where would I plug in position in the vertices array?
  float vertices[] = {
 -.5f,-.5f,0,
.5f,-.5f,0,
-.5f,.5f,0,
.5f,.5f,0
 };

shader.setup("Resources/Shaders/shape.vertex", "Resources/Shaders/shape.frag");

glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_DYNAMIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);

// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);


texts: Storing color and position (height and width) in an array which can be changed accordingly (bubble shooter)

texts:
How can I store the colors and position (i.e the position of the balls in bubble shooter game) using an array? I first tried using a simple loop but I think it won't work when I need the balls to burst so the balls should be printed using arrays. Here is my simple code

DrawLine( 380 , 60 ,   mx ,  my,10,  colors[BLACK]);
DrawRectangle( 1,89 ,799,500 , colors[WHITE]);
DrawRectangle(0 , 0,330 , 90 , colors[WHITE]);
DrawRectangle(430, 0, 380  , 90  , colors[WHITE]);

int zig=0;

int wide1=25;
int high1=574;

for ( high1 ; high1>=80 ; high1=high1-50){
    for (wide1 ; wide1<=780 ; wide1= wide1+50 ) {
        DrawCircle(wide1 , high1 , 25 , colors[WHITE]);
    }
    zig=zig+1;
    if (zig%2==0){
        wide1=25;
    } else {
        wide1=50;
    }
}


texts: save player achievements in local device

texts: As  an indie developer with zero dollar budget for servers and backend i wonder if there are ways to store the player achievements on his mobile device ?


texts: Points evenly spaced along a bezier curve

texts:
I have looked around for a while and I can't find a solution to this problem.
Let's say I have a cubic bezier curve (defined by 4 points) and I want to get a set of points that are spaced evenly along the curve. Think of placing a text along a curve for an example.

Now the problem is that if I input t (interpolation value from 0-1) with a constant increment the points are not evenly spaced. The distance along the curve is smaller when the curve makes a turn and longer when the curve is straight.

So how do I place points evenly along a bezier curve?


texts: What is the difference between GetComponent() and Find() in Unity?

texts:
I'm just learning to develop in Unity. One simple thing I'd like to do is change the colors of objects programmatically.  I have a compound asteroid prefab object, in which the meshrenderer and material is inside the child component asteroid_prop_01.

After reading the Unity docs and previous programming posts, I was able to do this successfully with GameObject.transform.Find(), but I don't understand why GameObject.Find(), GameObject.transform.Find() and GameObject.GetComponent() are not equivalent.

I'd really appreciate an understanding of the difference.  E.g. all these methods are based on the particular GameObject instance assigned to clone, so why aren't they all returning the same specific instance of clone.prop_asteroid_01.renderer.material.color?

eGameObject clone = (GameObject) Instantiate (hazard, spawnPosition, spawnRotation);
// This works
clone.transform.Find("prop_asteroid_01").renderer.material.color = Color.blue;
// This fails at compile time: "Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name instead"
clone.Find("prop_asteroid_01").renderer.material.color = Color.blue;
// Fails with runtime error "Object reference not set to an instance of an object"
clone.GetComponent("prop_asteroid_01").renderer.material.color = Color.blue;

Thanks for your help.


texts: Sprites do not refresh/reimport with ScriptedImporter using the SpriteEditor

texts:
I've created an importer for Aseprite-Files with the ScriptedImporter classes.
I'm working on supporting the latest features of Unity like the secondary texture and this should work without bigger issues.

The current issue I'm facing is when I change the sprites in the Sprite Editor or from a feature of my own, the asset won't get changed in the project-window unless i switch to another folder and switch back.

Do I have something wrong in my importing order or is something missing? I tried to refresh or reload the asset in the AssetDatabase but that didn't worked.

The OnImportAsset method looks like the following. I implemented the ISpriteEditorDataProvider to support the sprite-editor.

    public override void OnImportAsset(AssetImportContext ctx)
    {
        name = GetFileName(assetPath);
        _aseFile = ReadAseFile(assetPath);

        GenerateAtlasTexture();

        if (spriteImportData == null || spriteImportData.Length == 0)
        {
            SetSingleSpriteImportData();
        }

        GenerateTexture(ctx.assetPath);

        ctx.AddObjectToAsset("Texture", texture);
        ctx.SetMainObject(texture);

        foreach (Sprite sprite in sprites)
        {
            ctx.AddObjectToAsset(sprite.name, sprite);
        }
    }

With the GenerateAtlasTexture method I create a sprite-atlas out of the aseprite-file.

I had to create my own SpriteImportData class because Unitys struct won't get stored through the serialization process and I have to store the import settings of each sprite in a way.

The GenerateTexture method uses Unitys own TextureGenerator class to generate the textures or sprites and store them in a instance-variable called sprites.

Here is the link to the repo. It is currently in the "sprite-editor" branch. https://github.com/martinhodler/unity-aseprite-importer/tree/sprite-editor

Thanks a lot


texts:
I am currently working on a basic minecraft like game.
I have a list of coordinates using which i render instances of a cube model.
To optimize my rendering, i need to merge similar adjacent cubes into a single largest possible cube so that the total number of polygons that needs to be rendered is reduced

Any suggestions?


texts: Splitting a character model to ease animations

texts:
I've recently been looking into animations within Unity, and came across the idea of splitting my humanoid character's object into two at the waistline. The Idea being that animations used for movement can be applied to the legs, without interfering with general upper body animations/stances (and vice versa). Is this a viable option and would there be any adverse effects from doing this?

Also, is there any real need? I've noticed Unity is quite flexible when it comes to animations, but am unsure whether unity would be able to handle this? My main issue is different weapon types, where I would like the hands in different idle positions, but without having to have 4 or 5 different running forward animations.


texts:
I'm not an animation artist and so I want to create some animations for testing.
I want to use a camcorder to record me while I'm running and so
I want to know if exists a software that grab the video and translate it
in animation frames.


texts:
I got a question regarding rendering a 2D text over the 3D scene in OpenGL 3.3. I followed this tutorial about how to render text in OpenGL. Although the tutorial is for C++ i ported it to Java (Kotlin), but I can't see any text rendered.
Basically, what I am doing:

Use program for 3D scene
Render the 3D scene with proper view/projection matrix
Use program for text rendering (basically vertex shader and fragment shader from the tutorial)
Render text with ortho matrix

However, I do not see my text rendered. I went through some question here, which look similar, but they use the old OpenGL and their answers look like mine solution, I am using.

Does any of you have any advice on how to render 2D over 3D properly?
Thanks

UPDATE with code:

// buffer setting up
glBindBuffer(GL_ARRAY_BUFFER, fontBuffer)
glBufferData(GL_ARRAY_BUFFER, BufferUtils.createFloatBuffer(24), GL_DYNAMIC_DRAW)

glBindVertexArray(fontArray)
glBindBuffer(GL_ARRAY_BUFFER, fontBuffer)
glEnableVertexAttribArray(fontProgramCache[FontProgram.POSITION])
glVertexAttribPointer(fontProgramCache[FontProgram.POSITION], 2, GL_FLOAT, false, 4 * java.lang.Float.BYTES, 0)
glEnableVertexAttribArray(fontProgramCache[FontProgram.TEXCOORD])
glVertexAttribPointer(fontProgramCache[FontProgram.TEXCOORD], 2, GL_FLOAT, false, 4 * java.lang.Float.BYTES, 2L * java.lang.Float.BYTES)

Now within the main loop:

glEnable(GL_DEPTH_TEST)
// 3D models
modelsToDraw.forEach(::draw3dModel)
glDisable(GL_DEPTH_TEST)
// text
renderText("HELLO ", 0f, 0f, 2f, Vector3f(0f, 0f, 0f))

the renderText function:

fun renderText(text: String, x: Float, y: Float, scale: Float, color: Vector3f) {
    var mutableX = x
    glUseProgram(fontProgram)
    glUniform3f(fontProgramCache[FontProgram.TEXT_COLOR], color.x, color.y, color.z)
    glActiveTexture(GL_TEXTURE0)

    glBindVertexArray(fontArray)
    val projectionData = BufferUtils.createFloatBuffer(16)
    orthoProjection.get(projectionData)
    glUniformMatrix4fv(fontProgramCache[FontProgram.PROJECTION], false, projectionData)

    for (c in text) {
        val character = characterCache[c] ?: continue
        val xPos = mutableX + character.bearing.x * scale
        val yPos = y - (character.size.y - character.bearing.y) * scale
        val width = character.size.x * scale
        val height = character.size.y * scale

        val vertices: Array<Array<Float>> = arrayOf(
            arrayOf(xPos, yPos + height, 0f, 0f),
            arrayOf(xPos, yPos, 0f, 1f),
            arrayOf(xPos + width, yPos, 1f, 1f),
            arrayOf(xPos, yPos + height, 0f, 0f),
            arrayOf(xPos + width, yPos, 1f, 1f),
            arrayOf(xPos + width, yPos + height, 1f, 0f))
        glBindTexture(GL_TEXTURE_2D, character.textureId)
        glUniform1i(fontProgramCache[FontProgram.TEXT], 0)
        glBindBuffer(GL_ARRAY_BUFFER, fontBuffer)
        val verticesBuffer = BufferUtils.createFloatBuffer(24)
        vertices.forEach {
            it.forEach {
                verticesBuffer.put(it)
            }
        }
        glBufferSubData(GL_ARRAY_BUFFER, 0, verticesBuffer)
        glBindBuffer(GL_ARRAY_BUFFER, 0)
        glDrawArrays(GL_TRIANGLES, 0, 6)
        mutableX += (character.advance shr 6) * scale
    }
    glBindVertexArray(0)
    glBindTexture(GL_TEXTURE_2D, 0)
    glUseProgram(0)
}

I think that the draw3dModel function is fine, as it does what it should.


texts: Compile time error handling for single programmer games?

texts:
Hey.
My input system has a GetKey() method that returns a key in a map. Simple enough.
However, I want to know if the key is not available - be it a typo, or misuse of wording, or something else.
I am the only person working on this project; would it be a good idea to simply set some compile time throw to see if it catches one? Is this even possible?
What I'm meaning is:
 if(entry is not found) { throw something("couldn't find key"); exit(); }
Rather than an approach of
if(entry is not found) { try and compensate somehow and continue }
And then go through the code and find where I've made a mistake. Of course, for a large project I would want real error handling like the second. But I can just get rid of these errors, since there's no modding. But I'm the only one working, so is this probably the easiest way to do it?
Well, it's this or make some kind of BLANK key and check it every query.
EDIT: I am using strings as my keys, so no translate functions would be easy.
Double EDIT: I bind commands (strings) to keys (wrapper over an enum value). It means it's more understandable to check if "move_left" has been pressed than if keyCode::A has been, as well as being more changeable.


texts: Object in Box2d doesn't sit perfectly on top of other object

texts:
I have a rectangle in my player class with the following properties

b2BodyDef player;
player.type = b2_dynamicBody;
player.position.Set(x + width, 10.17f - (y + height));

m_PhysicsBody = level->GetPhysicsWorld().CreateBody(&player);

b2PolygonShape shape;
shape.SetAsBox(width, height);

b2FixtureDef fixture;
fixture.shape = &shape;
fixture.density = 1.0f;
fixture.friction = 1.0f;

m_PhysicsFixture = m_PhysicsBody->CreateFixture(&fixture);
m_PhysicsFixture->SetUserData(this);

and another rectangle in my level class with the following properties

b2BodyDef ground;

ground.position.Set(x + width, 10.17 - (y + height));

b2PolygonShape groundBox;
groundBox.SetAsBox(width, height);

b2Body* m_Body = m_PhysicsWorld.CreateBody(&ground);

b2FixtureDef fixture;
fixture.shape = &groundBox;

fixture.friction = 1.0f;

m_PhysicsFixture = m_Body->CreateFixture(&fixture);

m_PhysicsFixture->GetShape()->ComputeAABB(&aabb, m_Body->GetTransform(), 0);

The problem is that unless the player object is a perfect square (the width and the height are exactly the same) it won't sit exactly on top of the ground object I created in the level class. It intersects it a little bit before coming to a rest. I've attached a picture so you guys can see.

The way that I render the shapes is as follows

b2AABB aabb;
m_PhysicsFixture->GetShape()->ComputeAABB(&aabb, m_PhysicsBody->GetTransform(), 0);

DrawRectangle(aabb.lowerBound.x * 100.0f, (m_Window.GetHeight() - (aabb.lowerBound.y * 100.0f)), (aabb.upperBound.x - aabb.lowerBound.x) * 100.0f, (aabb.upperBound.y - aabb.lowerBound.y) * 100.0f);

I multiply the values by 100.0f to make it bigger, and y is the height of the window minus y. This is because I'm using SDL, which sets the upper-left corner as the 0,0 origin. So all the way at the very top, y = 0, and all the way at the bottom, y = the window height.


texts: Top down four directional movement snap to tiles, not feel like crap

texts:
I want to make a topdown rpg movement, I need to update these parameters based on user input:
User input four directions: ⬆⬇⬅➡ .
Update parameters

Position: x, y,
Flip sprite: flipx, flipy,
Sprite number: s, eg: 1 for horizontal sprite, 17 for vertical sprite
Sprite Animation: si, eg: 1 to 4 for walking animation

This is my crappy implementation:
function _init()

p = {
   t=0,
   x=0,
   y=0,
   dx=0,
   dy=0,
   mtimer=0,
   s=1,
   si=0,
   flipx=false,
   flipy=false
}
end

function _update()

   local input_x = 0
   local input_y = 0

   if btnp(⬆) then
      input_y = -1
   elseif btnp(⬇) then
      input_y = 1
   end

   if btnp(⬅) then
      input_x = -1
   elseif btnp(➡) then
      input_x = 1
   end

   if p.dx == 0 and p.dy == 0 then
      if input_x != 0 then
         p.dx = input_x
         p.mtimer=4
      elseif input_y != 0 then
         p.dy = input_y
         p.mtimer=4
      end
   end

   if p.mtimer > 0 then
      p.mtimer -= 1
      p.t += 2
      p.x += p.dx * 2
      p.y += p.dy * 2
      if p.mtimer == 0 then
         p.dx = 0
         p.dy = 0
      end
   end
 p.t += 0.5

   if p.dx != 0 then
      p.s = 1
   elseif p.dy != 0 then
      p.s = 17
   end

   p.flipx = p.dx == 0 and p.flipx or p.dx < 0
   p.flipy = p.dy == 0 and p.flipy or p.dy < 0

   p.si = flr(p.t % 30 / 30 * 4)

end

function _draw()
   spr(p.s + p.si, p.x, p.y, 1,1, p.flipx, p.flipy)
end

This is the end result:

As you can see it's so bad looking, I want you to implement this movement so it's fun and juicy. Or what can I do to improve the looks and feel of this.


texts: Drawing more that one quad with only one glDrawArray call....?

texts:
Edit

After initially thinking that my sprite batch test was faster than calling each sprite individually, it appears that is not the case!! :-(

With a single set of GL calls for a each sprite, I can get about 90 quads to move with no performance degradation.

With my batching test I can get about 12 (all in one call).

The problem is that I can't find any examples (code) anywhere for how this can be achieved using Android (Java) and OpenGL ES 2.0.

My method involved passing in an array of coordinate sets instead of a single set of coordinates, and then the method would build an array to store these coordinates in and then render the relevant amount of vertices.  Like I say, it works but the performance is awful!! Is this the right approach?

Could anyone help? Thanks!

I'm using Android with openGLES 2.0 and I can't work out how to draw 2 (or more, but for the sake of simplicity, lets say 2 for the time being) textured quads using only 1 call to glDrawArrays.

My shaders are fairly standard and take into account sprite opacity as follows:

//vertex shader
    String strVShader =
              "uniform mat4 uMVPMatrix;" +
              "attribute vec4 a_position;\n"+
              "attribute vec2 a_texCoords;" +
              "varying vec2 v_texCoords;" +
              "void main()\n" +
              "{\n" +
              "gl_Position = uMVPMatrix * a_position;\n"+
              "v_texCoords = a_texCoords;" +
              "}";

//Fragment shader

    String strFShader =
        "precision mediump float;" +
        "uniform float opValue;"+
        "varying vec2 v_texCoords;" +
        "uniform sampler2D u_baseMap;" +
        "void main()" +
        "{" +
        "gl_FragColor = texture2D(u_baseMap, v_texCoords);" +
        "gl_FragColor *= opValue;"+
        "}";

Then my rendering method takes in vertices that set the position and size of the quad, set the texture, apply rotation (if any) etc...

And then draws with the following line:

GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

I've been looking for a couple of days now for examples of how this can be achieved, but nothing seems to explain how it is actually done.

Can anyone give me any clues?

Note: To keep the question short, I have omitted my actual draw method.  If this is required to give a fuller answer, please just ask and I will post.

Also please note that I need to do this as I'm trying to work out how to batch my sprites to increase performance.


texts: Unity - movement code overriding rigidbody mass?

texts:
Unity noob here...
I have a basic movement script, but whatever I set the objects mass at it still falls the same speed, floating down off ramps instead of sticking to the floor.
I saw some posts referencing that the movement translate can override the rigidbodys downward velocity. Well I tried several code adjusts but I couldn't get it to work correctly.
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

// this code is to keep movement direction when switching to alternate camera
if (Input.GetButtonDown("Horizontal") || Input.GetButtonDown("Vertical")) {
    viewForward = Vector3.Scale(Camera.main.transform.forward, new Vector3(1, 0, 1)).normalized;
    viewRight = Vector3.Scale(Camera.main.transform.right, new Vector3(1, 0, 1)).normalized;
    viewRight = new Vector3(viewForward.z, 0f, viewForward.x * -1f);
    }

moveDirection = v * viewForward + h * viewRight;
if (moveDirection != Vector3.zero) {
    // moveDirection.y = rb.velocity <-- not working
    transform.position += moveDirection * Time.deltaTime * moveSpeed;
    transform.rotation = Quaternion.LookRotation(moveDirection);
    }

Could someone point out what I'm doing wrong?


texts: Resize from one side of the object in runtime Unity

texts:
For now I managed to resize my object but it resizes always from the center. I have the same problem like this question here.

I've been thinking like adjusting the position and stuff, but nothing works for my code.
Here's my code

if (isMouseDragging)
    {
        //tracking mouse position.
        Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, positionOfScreen.z);
        //converting screen position to world position with offset changes.
        Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offsetValue;
        if(getTarget.CompareTag("LeftRightWall"))
        {
            currentPosition.y = getTarget.transform.position.y;
            currentPosition.z = getTarget.transform.position.z;
        }
        if(getTarget.CompareTag("FrontWall"))
        {
            currentPosition.x = getTarget.transform.position.x;
            currentPosition.y = getTarget.transform.position.y;
        }
        //It will update target gameobject's current postion.
        Vector3 v3Scale = getTarget.transform.localScale;
        getTarget.transform.localScale = new Vector3(v3Scale.x + 0.1f , v3Scale.y , v3Scale.z);
        getTarget.transform.position = new Vector3(mfX + getTarget.transform.localScale.x / 2.0f, 0 , 0);
        getTarget.transform.position = currentPosition;
    }

My idea is I want to make the gameobject tagged LeftRightWall will be resized whenever the FrontWall is dragged and vice versa, like adjsuting the room size but I want to know how to resize them first. Any ideas?


texts:
In D3D11, we have a DeviceContext, which represents the Renderpipeline.

In Metal, we have a RenderPipelineState.
In Metal, I cache the RenderPipelineState, it is the abstraction of a "material".

Is DeviceContext in D3D11 the same? I.e. 1 DeviceContext = "1 Material" or do I set the DeviceContext (BlendState,DepthState) whenever the Material changes?
My idea was to have a Material Class which holds a pointer to a DeviceContext and whenever i want to draw this material, i execute Draw*() on this context.


texts:
I am currently creating a 2D fighting game and have implemented a system where upon starting a new game, the player is presented with the option to create a custom character. I have a set of string arrays set with values that correspond to hair, headgear, chest, lower body and shoes.

When done selecting a variety of items from the lists, a code is generated based off the index of each item (i.e 01123), which is then used to assign the correct Spritesheet to the player character.

This has already presented a lot of work as I have had to create quite a few spreadsheets based of possible combinations, but I am now looking at a massive amount of work to implement each variation.

I have started to look into setting layers for each item to reduce workload, but I am also looking at having different stances for the character - Depending on the currently equipped weapon - so this may present a lot of work either way.

My question is, do I have any alternatives or am I stuck creating masses of Spritesheets to cover all combinations?

As a side note, how much impact will assigning layered items have on overall performance?


texts:
In the top of the script:

public AnimationCurve curve;

Then the object in the editor have AnimationCurve but without any curve yet:

I want to set one of the curves via the script in the Start.

For example to select this one the most one in the right:


texts:
I am trying to come up with a collision function where all the cases are made.

If the player (Who's hit box is a circle) collides with a platform (hit box is a rectangle) from the right the platform will push the player back.
If the player collides with the platform for the top the player will stand on the platform.
If the platform is to the left of the player the player cant move to the left.

I am not asking how to tell if they are colliding or not but which side of the platform they are collide with where each platform is it's own object.

Can someone help me make this function?


texts: How to make a 2d game with Ascii art assets

texts: I am new to game development and have been practicing programming games in godot. I am looking to make a minimalist game that uses simple ascii art however I am unsure if I should use UI elements to represent different elements of the game or if I should make each letter I want to use into a sprite.


texts: How can I create a smooth simulation for a fast-paced, multiplayer table hockey game?

texts:
I'm adding multiplayer to an iPhone game that we have in our company. It's a sort of 'table hockey' game, with a puck and two mallets.

It's a pretty fast game, so I need a smooth experience at both ends. What I'm doing right now is using Game Center, and setting up the iPhone that starts the game as the "server."

So, the client runs its physics the same as the server, but the server adjusts the speed of the puck on the client and adjust its position when they are going on the same direction. The problem that it has some glitches, when the physics simulations differs a bit between then and the server sends the command to correct and the client kind of jumps around.

Does anyone has a suggestion how should I can handle this? Or should I try a different way?


texts: Rotate arrow without using Unity3d physics engine

texts:
I have this code that simulates the movement of a projectile without using the unity physics engine

IEnumerator LaunchProjectile(int angle, float speed)
{

    // Move projectile to the position of throwing object + add some offset if needed.
    Projectile.position = transform.position + new Vector3(0, 0f, 0);
    Projectile.rotation = transform.root.rotation;
    Debug.Log(transform.root.eulerAngles);

    // Calculate distance to target
    float target_Distance = speed * (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);

    // Extract the X  Y componenent of the velocity
    float Vx = Mathf.Sqrt(speed) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
    float Vy = Mathf.Sqrt(speed) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);

    // Calculate flight time.
    float flightDuration = target_Distance / Vx;

    this.arrowSimulationScript = Projectile.gameObject.GetComponentInChildren<ArrowSimulation>();

    float elapse_time = 0;

    while (!arrowSimulationScript.Collided())
    {
        Projectile.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);

        Projectile.LookAt(Projectile.position - new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime));

        arrowSimulationScript.Velocity = new Vector3(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime).magnitude;

        elapse_time += Time.deltaTime;

        yield return null;
    }
}

The arrow is fired in the direction of the object which has this script attached. To make the arrow rotate I use this line of code:

Projectile.LookAt(Projectile.position - new Vector3(0,  (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime));

The arrow moves towards the right direction but with the tip facing the z axis direction, instead of the direction of the bow.
Here is a video of the problem:
https://www.youtube.com/watch?v=cyK6DXxTw_E

If I comment out that line of code the arrow fly with the tip facing the direction of the bow, but it doesn't rotate.


texts: Swift - How do I detect the exact point at which two "SKPhysicsBody(edgeFromPoint:" type physics bodies intersect in sprite kit

texts:
I have two physics bodies attached to two separate sprite nodes using Sprit Kit.  One is a vertical line and one is a horizontal line:

//sprite with horizontal physics body
spriteMatrix[i][j].physicsBody = SKPhysicsBody(edgeFromPoint: CGPointMake(0, tileSegmentHeight), toPoint: CGPointMake(tileSegmentWidth, tileSegmentHeight))
spriteMatrix[i][j].physicsBody!.categoryBitMask = self.surfaceCatagory
spriteMatrix[i][j].physicsBody!.contactTestBitMask = heroCatagory

//sprite with vertical physics body
self.hero.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointMake(self.hero.frame.width / 2, self.hero.frame.height / 2), toPoint: CGPointMake(self.hero.frame.width / 2, -20))
self.hero.physicsBody!.categoryBitMask = heroCatagory
self.hero.physicsBody!.contactTestBitMask = surfaceCatagory

What I'm want to do is test if they are intersecting on every frame, and if they are, return the x and y position of where they are intersecting.  Is this even possible?


texts: Is there is a way to mask sprites in Spriter?

texts:
I am very new to Spriter. I want a sprite to be only displayed when it is above particular sprite.

How can achieve this?


texts: What is the optimal way to store customisation options?

texts:
I am trying to understand the most optimal way of storing customisation options within a game, or to be precise, to store all the possible customisation options for multiple different objects.

For example, assuming we are making a game about tanks and their customisation, there will be several available tanks that the player can choose from and each of the tanks will have multiple different parts available; some parts will be shared across a few tanks, while some will be specific to a tank.

I was thinking about a relational database, but I do not know web development, so I was initially thinking to have a table with all the tanks and a table with all the parts, then create a linking table between the two and load the available parts based on the chosen tank; but I'm not sure if that would work, or if it would be the most optimal way of doing this.

I tried looking for an answer, but I'm not getting any good results. People mention using files, and then parsing the data, but I'm not sure how that will work on a large scale; multiple tanks with hundreds of customisation options.

What is the most optimal way to to do this? If at all relevant, I am using Unity 5.


texts: How to handle multiple effect files in XNA

texts:
So I'm using ModelMesh and it's built in Effects parameter to draw a mesh with some shaders I'm playing with. I have a simple GUI that lets me change these parameters to my heart's desire. My question is, how do I handle shaders that have unique parameters? For example, I want a 'shiny' parameter that affects shaders with Phong-type specular components, but for an environment mapping shader such a parameter doesn't make a lot of sense. How I have it right now is that every time I call the ModelMesh's Draw() function, I set all the Effect parameters as so

foreach (ModelMesh m in model.Meshes)
        {

            if (isDrawBunny == true)//Slightly change the way the world matrix is calculated if using the bunny object, since it is not quite centered in object space
            {
                world = boneTransforms[m.ParentBone.Index] * Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(position + bunnyPositionTransform);
            }
            else //If not rendering the bunny, draw normally
            {
                world = boneTransforms[m.ParentBone.Index] * Matrix.CreateScale(scale) * rotation * Matrix.CreateTranslation(position);
            }

            foreach (Effect e in m.Effects)
            {
                Matrix ViewProjection = camera.ViewMatrix * camera.ProjectionMatrix;
                e.Parameters["ViewProjection"].SetValue(ViewProjection);
                e.Parameters["World"].SetValue(world);
                e.Parameters["diffuseLightPosition"].SetValue(lightPositionW);
                e.Parameters["CameraPosition"].SetValue(camera.Position);
                e.Parameters["LightColor"].SetValue(lightColor);
                e.Parameters["MaterialColor"].SetValue(materialColor);
                e.Parameters["shininess"].SetValue(shininess);

                //e.Parameters
                //e.Parameters["normal"]

            }
            m.Draw();

Note the prescience of the example! The solutions I've thought of involve preloading all the shaders, and updating the unique parameters as needed. So my question is, is there a best practice I'm missing here? Is there a way to pull the parameters a given Effect needs from that Effect?

Thank you all for your time!