texts: Unity sprites rendering problems on Android

texts:
I'm creating a simple 2d game for android, with normal sprites and animations. The problem is that when I open the game on my smartphone (Samsung galaxy trend plus), The sprites are rendered this way:

Of course, this is not what should happen. Moreover, within the Unity editor everything works flawlessly. My settings for the export are:

Texture compressions: ETC2 (GLES 3.0) - Tested also with "Don't override"
Player settings

Default orientation: landscape
Use 32 bit display buffer: unchecked - tried also with this option checked
Rendering path: forward - tried also with Legacy Deferred
Static batching/Dynamic batching: both checked

Camera settings

Clear flags: Solid color - tried also skybox

I don't have any other scene, and this one has only one camera (I saw some topics where people were having problems because they had two or more cameras). The sprites are all .png images with transparence, except for the background, that has no transparence, but is lagging. There are three sprites which are animated using the spritesheet, but they're terribly lagging, and almost can't be seen in this screenshot. I really can't understand why, I'll continue to try, waiting for your answers. Thank you in advance!

EDIT:
If in the player settings the orientation is set to auto-rotate and the device is in portrait, all the sprites works perfectly!!! The problem is that my game is meant for landscape...


texts: XNA Video Playback on XBOX "Invalid operation exception"

texts:
I am able to play a video in windows in my project, but the same code fails on the XBOX at the _player.Play(_logo) line. The error message is:

"An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.dll"

Relevant code:

    public LogoScreen()
    {
        TransitionOnTime = TimeSpan.Zero;
        TransitionOffTime = TimeSpan.Zero;

        _content = new ContentManager(Game3.Instance.Services, "Content");

        _player = new VideoPlayer();
        _player.IsLooped = false;

        _sb = new SpriteBatch(Game3.GDM.GraphicsDevice);
    }

    public override void LoadContent()
    {
        _logo = _content.Load<Video>("Video/intro_logo");
    }

    private bool _started = false;
    public override void Update(bool otherScreenHasFocus,
        bool coveredByOtherScreen, bool coveredByPopup)
    {
        if(_started == false)
        {
            _player.Play(_logo);
            _started = true;
        }

        if (_player.State == MediaState.Stopped)
        {
            Exit();
        }
    }

Here is the random test video that I'm using:
http://olhovsky.com/xna/intro_logo.wmv

Any ideas why this might be failing?


texts: What should be taken into consideration when choosing a math library for games?

texts:
I'm currently selecting a C++ math library to use for a project. There are several questions here and on SO concerning the 'best' library available and many answers with different suggestions, but I would like to run some tests on each of them before I make a decision.

I would like to select a library that will cater for my current needs but also for any needs in any projects I may work on in the future. My problem is that due to being fairly new at this, I'm not entirely sure what those needs will be yet.

Aside from the points that I can think of listed below, and assuming that I will only test libraries with a suitable license, what other commonly used features should I test/look for before making a selection?

Matrix operations - including addition, subtraction, multiplication, inversion, transposition, translation, rotation, scale
Vector operations - cross/dot product, normalisation, zeroing, magnitude, length2, scalar operands, normal calculation
Euler angle + Quarternion operations - rotation, interpolation, conversion, inversion, multiplication
Coordinate system conversion (Cartesian, spherical)
Random numbers - generator speed, period, statistical randomness
Possibly noise generation
Ease of integration with gl functions like glTranslate()

Also, assuming these libraries have been tested for mathematical accuracy, are there factors other than ease of use (documentation, mailing list/developer access), speed (vectorisation, SIMD), and memory usage to consider?


texts:
I am writing a 3D renderer that would render 3D models as if they had been drawn in halftone.
Feature-wise I need nothing fancy - no colors, just pure 3D geometry and basic lighting like here:
Image credit: https://blenderartists.org/forum/showthread.php?438820-Suzanne-Sketch

Notes:

I have written a basic 3D renderer in the past, however, I am really inexperienced when it comes to shaders (again, I do know basics) and I have absolutely no idea where to start with this.
The example image has been created in Blender, but I am writing my custom renderer.
This is not a duplicate of "How can I make a shader effect that looks like a lightly shaded pencil drawing?", as my input is a 3D model, whereas the OP in the linked question used an image.


texts: Will any program written with XLib work on any desktop environment (Gnome, KDE, etc.)?

texts:
I'm making an application that uses Win32 API on Windows but I want to support linux distros too.

Some people say linux doesn't have a native GUI API like Win32 API of Windows.

But I found XLib and it seems like it is somethink similiar to Win32 API. If I use XLib on my project, can I compile and run it on any linux distro that uses any desktop environment without using external libraries?

I don't want to use something like GTK+ or SDL because I'm learning Win32 (just for fun) and using a platform independent library along with Win32 API sounds really absurd.


texts: Detecting which side of the collider is hit

texts:
We are trying to determine which side of the collider is hit in order to let the colliding object pass through or land on the other object.

Our previous failed attempts included detecting object velocity and changes on Y axis in our 3D game with locked Z axis (simulated 2D).

Currently, the detection is working by calculating the velocity - when the "Object in motion" hits the top of the black cube ("trigger collider") by the  certain level of velocity (determined by gravity) the "collider" is activated. Otherwise, when the velocity is higher - the "object in motion" passes through. This, of course introduced a lot of issues and the solution itself is not elegant.

In the other scenario, we have tried adding trigger colliders around the "static object". This also complicates the process when "object in motion" has an arc when landing. Likewise, this solution is hard to maintain and prone to bugs.

On top of that, we implemented Raycasting. But we are not getting consistant "Top" and "Bottom" trigger indications when using it. Here is the gist of that code.

 void OnCollisionEnter(Collision collision)
 {
     if (collision.gameObject.tag.Equals("my_cube"))
     {
         var hit = HitDirection();
         Debug.Log(hit);
     }
 }

 bool IsRightOrLeftHit()
 {
     RaycastHit hit;

     Ray rayUp = new Ray(transform.position, Vector3.up);
     Ray rayDown = new Ray(transform.position, Vector3.down);

     Physics.Raycast(rayUp, out hit);
     Physics.Raycast(rayDown, out hit);

     return hit;
 }

We would appreciate any hint or help, and please ask me any questions if the explanations are not clear enough.


texts: Can I develop on the Oculus Rift with below the minimum required hardware?

texts: I have tried to see if my GTX 960m supports VR and sadly it seems I need minimum GTX 970m, still I have seen videos that if you overclock your 960m you can get a decent 115 frames. My question is, can I still develop games for the Oculus Rift in my 960? I can't afford now to buy assets, oculus and a new laptop.


texts: Calculation correct position of object after collision (2d)

texts:
I have a circle, that bounces of walls. The circle is traveling at the speed defined by px/s for x and y. I have collision detection implemented and I use vectors to calculate the new x/y speed (and direction) after the collision. My problem is, that is some cases the circle gets stuck in or is consumed by the wall.

The reason for this is, that when the collision occurs, the circle is actually x pixels inside the wall (as illustrated by the image below) and not just at the "border" of the wall. This occurs because the circle might move multiple pixels on each redraw (tick). The circle doesn't move enough pixels during the next redraw in order to get loose from the wall, thus triggering a new collision. Direction changes again towards the wall leading to a shaking motion of the circle, either finally getting loose of the wall or being consumed by the wall.

The solution for this is to reposition the circle so that it is loose from the wall after the collision has occurred. My problem is, that with my rusty mathematics, I can't figure out how to calculate the correct position of the circle and that's where I need your help.

I also wonder, how exact I need to be with the position, I mean, I know the minimum distance of the middle of the circle to the wall (and thus also know how much the circle has penetrated the wall), let's call this value d. I could of course move the circle d pixels perpendicular to the wall, this might be a close enough approximation of the position, although not 100% accurate. If you guys think this is a good enough solution, is there a way to achieve this with vectors or do I need to calculate the angles and new position "manually" using cos and sin?

Side note: I'm not using SAT for collision detection because I have concave polygons.


texts: Performance problem with BufferedImage and AlphaComposite

texts:
I'm currently making a 2D platformer game and now I want to implement Light using AlphaComposite. For creating the lights I first create a blank BufferedImage with ARGB format. After this, I create darkness by filling a black transparent rectangle over my screen. Now I am using AlphaComposite.DST_OUT and an image with an white cirle. When I render the white circle, the black darkness will be eliminated caused by the AlphaComposite. Lastly, I render this BufferedImage to my main BufferedImage where all the rendered stuff comes together. As you can see on the picture it works fine but when I resize my game it starts to lag extremely. Without using the light system the game actually runs perfect in fullscreen, as well.

Here is an extract of my code where I render my lights:

public void render(Graphics2D g) {
    BufferedImage image = new BufferedImage(GamePanel.width, GamePanel.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    g2.setColor(new Color(0,0,0,210));
    g2.fillRect(0, 0, GamePanel.width, GamePanel.height);

    Composite old = g2.getComposite();
    AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_OUT, 1.0f);
    g2.setComposite(ac);
    g2.drawImage(Light.LIGHT, 50, 25, null); //here i render the image with the white cirle
    g2.setComposite(old);

    g.drawImage(image, 0, 0, null); //drawing lights to the main bufferedimage
}

The last line g.drawImage(image, 0, 0, null); is where I render the light to my main BufferedImage where all the rendered stuff is rendered, as well.

This is how I render my main BufferedImage:

@Override
public void paintComponent(Graphics g) {

    Graphics2D g2d = image.createGraphics();
    g2d.setBackground(new Color(146, 189, 221));
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    gamestatemanager.render(g2d);

    g.drawImage(image, 0, 0, width, height, null); //scaling the main bufferedimage
}

Do you have some Ideas for me?

EDIT The game also starts lagging in fullscreen when I just paint the black rectangle.


texts:
We've been trying to replicate the most common blending modes that are available in Photoshop and Quartz 2D, but we've only come up with 3 and that's after some long searching online.

For anyone interested, here they are:

  Multiply = GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA
  Screen = GL_MINUS_DST_COLOR, GL_ONE
  Linear Dodge = GL_ONE, GL_ONE

You can try these and other such modes in action online, at this very useful website: http://www.andersriggelsen.dk/glblendfunc.php

Now, we would appreciate it if anyone could provide us with additional blending modes that we can recreate inside Cocos2D, since our Open GL experience is really, really limited.

Thank you in advance!

Argiris


texts: Best way to generate a sports schedule with restrictions, byes and rest days

texts:
I have created a schedule generator to match games to calendar dates with some restrictions, after some review it does not run in an usable time.

The schedule is for a 2 conference, 4 divisions, 6 teams league with two byes (not on the first 4 or last 4 weeks), teams that play in the same stadium cannot play at home in the same day.

It's a 24 week season, each team plays 10 division games(5 at home, 5 away), 6 games against a division in the conference (3 home, 3 away), 6 games against a division in another conference (3 home, 3 away) and 2 more games against the teams in your conference that had the same standing as you last year in the conference division you didn't play against.

When you play a different division if you play at home, next time you face that division you will play away and vice-versa.

My approach was to create all the games, handpick the restrictions first and then just randomly try to fit all the games until I get a working schedule. Also tried a depth first solution without success.

Are there any solutions out there that allow to calculate this schedule in at most 1 hour? Preference would be almost instantly, don't know if it's possible.


texts: How to achieve 'forward' movement (into the screen) using Cocos2D?

texts:
I'm interested in creating a 2.5D first-person shooter (like Doom) and I currently don't understand how to implement the player moving forward. The player will also be able to browse around the world (left, right, up, down) via gyroscope control. I plan to only use 2D sprites and no 3D models.

My first attempt was to increase the scale of layers to make it appear as if the player was moving toward the objects but I'm not sure how to make it seem as if the player is passing around the objects (instead of running into them).

If there are extensions that I should take a look at (like Cocos3D), please let me know. Thanks for the help!


texts: NegaScout with Zobrist Transposition Tables in Chess

texts:
I'm trying to put Transposition tables into my alpha beta scout. I do see an incremental speed boost I think toward mid or late game, however, even with a table size of 1-2GB, its may or may not be slower than just not reading from the Transpose table at all. I'm also noticing some less than efficient moves if I were to play the exact same game without the tables.

I tested my Zobrist key hashing, and they come out properly even after making and undoing moves. I don't believe they are the issue. I tried to follow the advice of these articles in designing the alpha/beta pruning.
http://web.archive.org/web/20070809015843/http://www.seanet.com/~brucemo/topics/hashing.htm
http://mediocrechess.blogspot.com/2007/01/guide-transposition-tables.html

Can anyone help me identify a mistake? Perhaps I'm not understanding the evaluation of checking alpha vs beta from the hash. Or is 1-2GB too small to make a difference? I can post more of the Transposition table code if need be.

 public int alphaBetaScout(Board board, int depth, int alpha, int beta, bool color, bool
quiscence)
{
    // !!!! With or without this specific section, and any other Transpose.Insert, doesn't make the game play or evaluate any faster.
    HashType type = HashType.AlphaPrune;
    HashEntry h = Transpose.GetInstance().Get(board.zobristKey);
    if (h != null)
    {
        if (h.depth >= depth)
        {
            if (h.flag == HashType.ExactPrune)
            {
                return h.scored;
            }
            if (h.flag == HashType.AlphaPrune)
            {
                if(h.scoredState > alpha)
                {
                    alpha = h.scored;
                }
            }
            if (h.flag == HashType.BetaPrune)
            {
                if(h.scoredState < beta)
                {
                    beta = h.scored;
                }
            }
            if (alpha >= beta)
            {
                return alpha;
            }
        }
    }

    if (board.terminal)
    {
        int scoredState = board.Evaluate(color);
        Table.GetInstance().Add(board.zobristKey, depth, Entry.EXACT, scoredState);
        return scoredState;
    }

    //May do Quescience search here if necessary && depth = 0

    Stack movesGenerated = GeneratePossibleMoves();
    while(!movesGenerated.isEmpty())
    {
        int scoredState = MAXNEGASCOUT;

        board.MakeMove(movesGenerated.pop());
        int newAlpha = -(alpha +1)
        scoredState = -alphaBetaScout(board, depth - 1, newAlpha, -alpha, !color, quiscence);

        if (scoredState < beta && alpha < scoredState)
        {
            scoredState = -alphaBetaScout(board, depth - 1, -beta, -scoredState, !color, quiscence);
        }

        board.UndoMove();

        if (scoredState >= beta)
        {
            Table.GetInstance().Add(key, depth, Entry.BETA, beta);
            return scoredState;
        }

        if (scoredState > alpha)
        {
            type = HashType.ExactPrune;
            alpha = scoredState;
        }
    }
    Table.GetInstance().Add(key, depth, type, alpha);
    return alpha;
}


texts:
We're are trying to get the direction of a projectile but we can't find out how

For example:

[1,1] will go SE

[1,-1] will go NE

[-1,-1] will go NW

and [-1,1] will go SW

we need an equation of some sort that will take the player pos and the mouse pos and find which direction the projectile needs to go.

Here is where we are plugging in the vectors:

def update(self):

    self.rect.x += self.vector[0]
    self.rect.y += self.vector[1]

Then we are blitting the projectile at the rects coords.


texts: Is ETC2 Texture Compression available in OpenGL ES 2.0?

texts: I have an ES 2.0 app and would like to use ETC2 texture compression if it is available (i.e. I am running on a device that supports ES 3.0 standard).  Is it possible to use ETC2 in ES 1.1/2.0, and if so how can I query if a device supports it?  For most forms of texture compression, there is an extension I can query for, but there is no extension for ETC2 since it is built in.


texts: Why does Resources.Load cause a CastException in this case?

texts:
I am doing this:

string fontName = "freespin_big";

TextAsset xml = Resources.Load<TextAsset>(fontName);
Texture2D image = Resources.Load<Texture2D>(fontName);

Font font = Resources.Load<Font>(fontName);
if (font == null)
{
    font = new Font();
    AssetDatabase.CreateAsset(font, "Assets/Resources/" + fontName);
}

In Resources, we have freespin_big.png and freespin_big.xml. I am planning to import the png and xml and create a font. So I check if the font object is there, if not create it.

But I get this error if the font does not exist yet:

  InvalidCastException: Cannot cast from
  source type to destination type.

If I try to do this:

Font font = Resources.Load<Font>("blorg");

Where no files are named "blorg", I get null as I expect.

Shouldn't Resources.Load return null if it finds no fonts with the right name?


texts:
I'm trying to make my very tiny man pathfind his way through a map of a school but the navmash won't recognize some of the hallways cause they are very narrow like this.

So as you can see the man can fit but the navmesh says no so can anyone help and keep in mind that i am very new to unreal engine so please make your explanation easy to understand.


texts: How to apply forces to rigidbody when Time.timeScale is changed?

texts:
My Task:
I'm trying to replicate this virtual 3d creature evolution project. I'm using unity as my physics engine.
Each limb part has a MonoBehaviour called an Effector. The effector is what makes the creature move by applying forces to it using Rigidbody.AddRelativeTorque(Vector3 torquVector). I want the effector to act at contant frequency, relative to time (even when scaled). Meaning, if on time scale 1, the effector acted 10 times a second (real-time), a time scale of 10 will cause it to affect 100 times a second (real-time)

I'm changing Time.timeScale during the evolution to speed things up, but I'm sure I'm missing something in the force calculation.

My code:

    void FixedUpdate()
    {
        // Apply force
        if (Time.frameCount % 10 != 0)
           return;

        float val = GetEffectorValue(); // Some calculated value
        float delta = Time.fixedDeltaTime * Time.timeScale;
        float force = val * TORQUE_WEIGHT * rb.mass * delta;

        Vector3 forceVector = Vector3.zero;

        // There are 3 effectors, each one operates on a differet axis
        if (axis == Axis.X)
            forceVector.x = force;
        else if (axis == Axis.Y)
            forceVector.y = force;
        else if (axis == Axis.Z)
            forceVector.z = force;

        rb.AddRelativeTorque(forceVector);
    }

The problem:
The movement changes with the time scale. When the time scale is low, a creature doesn't really move (which is expected), but when the time scale is upped to 10 or more it is obvious that it moves more. In order to be sure that I'm not impatient and don't wait long enough I compared a 30 second period with a time scale of 2, to a 6 second period with a time scale of 10.

I tried a couple of other methods and looked at the unity documentation but couldn't figure this one out.

Thanks in advance :)


texts: AS3 Symbol not showing returns no errors?

texts:
I haven't touched Flash in a while and I've forgotten a lot.

I'm trying to get a space-ship symbol to show in the middle of the screen. For some odd reason it isn't showing in the middle of the screen or even appearing. There's no error in the output or an error in the debug.

Here's some code below.

I'm coding in Coda 2 and using Flash to manage the library. I currently only have one class called Game.As and the ship symbol is a MovieClip with the name shipSymbol and the class is defined as shipBase with the base class being flash.display.MovieClip;

package {

import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.events.Event;

public class Game extends MovieClip {

    //Spaceship Symbol
    private static var ship = spaceShip;

    private function initShip(startX = number , startY = number):void {
        ship = new spaceShip();
        this.x = startX;
        this.y = startY;
        startX = stage.stageWidth /2;
        startY = stage.stageHeight /2;
        stage.addChild(spaceShip);
        trace("Space-Ship Spawned");
    }
    public function runGame():void {
        stage.addEventListener(Event.ENTER_FRAME , update);
    }
    override public function update(e:Event):void {
        initShip();
    }
}

}

Thanks, for the help :P


texts: Concept design-pattern for industry simulation required

texts:
I am making a mobile game simulating industry. A brief high level description is below.
A hub could be thought of as a base/city, within which there are rooms/buildings which determine what is produced and consumed.
Rooms/buildings need people to work them.
People have their own produced and consumed resources that need to come from rooms/buildings.
The buildings like machines in a production line have paths of commodity flow defined.
How to implement people with their own needs like thirst, sleep and illness while coordinating the buildings is causing me trouble.
I know many games have this same premise but can’t turn up enough info on their workings to help me. The real challenge is that I do not want to run the game where time passes relatively slowly and each person can move around and make decisions constantly.  I want to be able to change the speed of the game, likely from running a day every 30 seconds to a month every two minutes. So was focusing more on when changes to the system were occurring.
The number of hubs is likely to reach 80 each with 20 rooms and say 30 people to give an idea of scale.
Do you have any example games or coding approaches that could help light my way? Each concept I think through falls over.
Your help is very much appreciated and thanks for reading! If I have not included enough details please let me know, it is my first post so unsure how far to go into it.


texts: Android BitmapFactory.decodeStream loading BGR format?

texts:
It is very odd.I want to load .png file via asset manager which is provided by android sdk.
            AssetManager manager;
/........./
BitmapFactory.decodeStream(manager.open(path));

It returns BGR format data but opengl es 2.0 uses RGB format so , Blue seems red , red seems blue, how odd.

Is there any solution for it?

I use Nvıdia Tegra 2 (Android 2.2) device for test the application along with c++ via JNI.


texts: Is there a reason to inherit both generic and non-generic version of an interface?

texts:
I've just gotten into some C# programming and decided to expand my knowledge of how games are made in C# by looking through some open-source frameworks. While doing this I noticed something very odd; classes that they make would implement both generic and non-generic interfaces that represent the same data structure. For example:

public class SomeSpecialList<T> : IList<T>, IList {
    ...
}

I couldn't find any explanation to this - Is this something I should be thinking about when programming games in C#? Why? Is it a performance thing?


texts:
I'm getting this error:

  Runtime NavMesh Builder source mesh combined mesh is skipped because
  it does not allow read access

I checked all the models and it has the read permission. I also noticed, that in some cases unchecking the static checkbox helps and I'm getting a smaller amount of these errors.


texts: Camera follow rotating ball - ortogonal direction

texts:
I have a ball, that has been moved via addForce. It colides in the scene with objects, leading to rotation in all axes.

I want a camera to follow this ball but from the side (direction ortogonal to the move vector and UP vector).
No matter what I do, I cannot get this working. The closest I get is almost correct, but camera "bumps" during frames.

I have used this in camera script to attach camera to the ball and move it with it:

this.transform.LookAt(this.cannonBall.transform.position, Vector3.up);

this.transform.position = ball.transform.position;

No I need to rotate camera 90 degree aroun up axis and move it a little backward to track ball from the side.

How can I achive this? If I use

this.transform.Rotate(Vector3.up, 90, Space.World);

It mess up lookAt


texts:
I am developing an XNA game and am trying to improve the performance of the game by hiding objects that are not visible to the user.

My first thought was to use a BoundingFrustum based on the camera's view and projection matrices, and then only draw objects whose BoundingBox collides or is inside the frustum. However, trying to do this gave me very unpredictable results, with objects disappearing before going out of view and sometimes not showing at all at certain camera angles.

Has anyone else implemented a successful solution to improve their game's performance?


texts: Unity dynamic light isn't casting shadows

texts:
I am using the Lightweight Scriptable Render Pipeline 1.1.11-preview and I have two lights in the scene. One is a Sun light and another is an uplight. The Sun light is set to cast dynamic shadows, as are the particle effect clouds and the models. I am expecting the clouds and the cloudship (the floating thing in the middle of the picture) to cast shadows.

The sand is procedurally generated: a flat prefab is loaded at run time and the y points are set by Perlinn noise. I recalculate the normals using Unity's method.

Here is the scene:

The properties of the Sun light:

The prefab for the sand (which I am expecting to have shadows):

Here is the lighting properties.

The setting window for the Lightweight Pipeline:

The settings for the mesh that should be casting the shadow:

Is there anything I'm missing? Thanks in advance.


texts: How to detect if players alter game files and stop them from entering the game server

texts:
as the question says.

how can i check if a player modifies a file such as maps or spells in my rpg games that will be located as "/cache/spells", "/cache/maps" or "/cache/entities" and you get the point.

all the files are going to be written in .xml if that matters and the game will be an online game made in java. not a browser game btw


texts: How I support different display resolutions?

texts:
I'm developing a 2D windows phone game. The game should look the same on every windows phone device. But I have no idea what to do so that my game looks great on every display resolution. How can I do that? What is the best/easiest way?

I don't like letterboxing. So I tried scaling the sprites but that looks blurry(very bad).
My sprites are all in PNG format. I created them in Inkscape.


texts: How do I check if a key is down in XNA when I'm only given a string that has the key's name?

texts:
I'm trying to get access to the keyboard state in XNA from an embedded JavaScript runtime.

I'd like to do something similar to the following, but I can't seem to figure out how to get from "Left" to Keys.Left, in one line, for all 100+ keys or so.

js.SetParameter("XNA_Keyboard", new {
    keyDown = (Func<string, bool>)((name) => {
        return keyboardState.IsKeyDown(Keys[name]); // ! Can't index keys enum by name
    }),
});

Is there some kind of reflection that will make this easier?


texts:
I have come across a very wierd problem. Here is my code:

#include <iostream>
#include "SDL.h"

using namespace std;

class MyGame
{
public:

    SDL_Surface* image;
    SDL_Surface* window;
    SDL_Event* e;

    void Start()
    {
        SDL_Init(SDL_INIT_EVERYTHING);

        window = SDL_SetVideoMode(800,600,32,SDL_SWSURFACE);

        image = SDL_LoadBMP("Bitmap.bmp");
        SDL_BlitSurface(image,NULL,window,NULL);
        SDL_FreeSurface(image);

        SDL_Event evt;

        bool programrunning = true;
        while(programrunning)
        {
            SDL_WaitEvent(&evt);
            if(evt.type == SDL_QUIT) programrunning = false;
        }

        SDL_Quit();
    }

    void Update()
    {
        SDL_Flip(window);
    }
};

int main(int argc,char* args[])
{
    MyGame obj;
    obj.Start();
    while(true)
    {
        obj.Update();
    }

    return 0;
}

Whenever I run this code on Code::Blocks, no errors appear and everything works except for the bitmap. For some reason it doesn't display. However, I once tried replacing Bitmap.bmp with cb.bmp (the Code::Blocks logo that came with the IDE) and it rendered perfectly fine. Also, whenever I close the program Windows gives me this error: "2DGame.exe not responding", no matter what bitmap I use. This is one of the strangest coding problems I have come across ever, please tell me why Bitmap.bmp is being a jerk and how to fix it and also how to fix the error I get whenever I close my program. Thanks!

P.S: You guys asked for the image, here it is:


texts: Is this really the reason for smoother movement?

texts:
Actually i'm watching a tutorial series on youtube about 2D Game programming in Java.
My question is about the player-movement.

The first version:

        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if(key == KeyEvent.VK_RIGHT) {
                player.setX(p.getX() + 5);
            }else if(key == KeyEvent.VK_LEFT) {
                player.setX(p.getX() - 5);
            }else if(key == KeyEvent.VK_DOWN) {
                player.setY(p.getY() + 5);
            }else if(key == KeyEvent.VK_UP) {
                player.setY(p.getY() - 5);
            }
        }

The problem in this first version is, that if you press now for example VK-RIGHT (and holding it), than the figur in the game moves first one step to the right, then stops for a half second or so and then the figur moves constantly to the right.
The problem here is the stopping, which takes a half second or so. This is not smooth.

Then the author of the tutorial presented a second, better version:

        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();

            if(key == KeyEvent.VK_RIGHT) {
                player.setVelX(5);
            }else if(key == KeyEvent.VK_LEFT) {
                player.setVelX(-5);
            }else if(key == KeyEvent.VK_DOWN) {
                player.setVelY(5);
            }else if(key == KeyEvent.VK_UP) {
                player.setVelY(-5);
            }

        }

        public void keyReleased(KeyEvent e) {

            int key = e.getKeyCode();

            if(key == KeyEvent.VK_RIGHT) {
                player.setVelX(0);
            }else if(key == KeyEvent.VK_LEFT) {
                player.setVelX(0);
            }else if(key == KeyEvent.VK_DOWN) {
                player.setVelY(0);
            }else if(key == KeyEvent.VK_UP) {
                player.setVelY(0);
            }

        }

and the tick() method in the Player.java:

public void tick() {
    x += velX;
    y += velY;
}

The author said, that the second version is smoother, because we don't need to ask first with the get-methods the actually value of x/y.
Is this really the reason, why the second method is smoother respectively we don't have still this stop for a half second or so?

If this is really the reason, why the start time of the player figur is in both version the same? In the first version the player figure would then have to need more time to start movement? But this is not the case! The difference is this stop for a half second or so after the first steop of movement is finished.


texts:
I am starting on the graphical portion of my project and before I begin I need to get Instancing working.  I can do instancing with SharpDX, but not with the Toolkit Models. The main reason I want to use the Tookkit is for loading models, textures, fonts, etc...

The most helpful thing for me would be a link to an example that instances a SharpDX.Toolkit.Graphics.Model -- but anything the shows the Model working with a custom effect should be fine... I can make instancing work from there right?

I have searched and searched for that though so I am not too hopeful - so if this is not something easily done alternative solutions would be great. As I said, I can use SharpDX without the toolkit just fine - but I want the benefits that come with loading models and fonts mostly.


texts:
I have a cursor object (simple quad) that I'm moving around above a floor mesh. The floor mesh has varying heights (hills and such).
How can I set my quad to sit at the same angle as the mesh floor?
I'm using a raycast to cast down on the position of the cursor and get the angle of the floor mesh using hit.normal, then reflect.
RaycastHit hit;
var rayStart = new Vector3(transform.position.x, transform.position.y + 5f, transform.position.z);
if (Physics.Raycast(rayStart, Vector3.down, out hit, 10f)) {
    if (hit.collider.tag == "Floor") {
        Vector3 incomingVec = hit.point - rayStart;
        Vector3 reflectVec = Vector3.Reflect(incomingVec, hit.normal);
        cursorSprite.transform.eulerAngles = reflectVec;
        }
    }

(I've left out the position code, that works, its just the angle code that doesnt)
I've tried a bunch of variations, altering the reflectVec angle x, y and z but I can't figure out how to get it correct :/


texts: How can I implement hexagonal tilemap picking in XNA?

texts:
I have a hexagon tiled map in which I need to check when a hexagon is clicked. The hexagons aren't actually touching, rather they have a slight gap in between each of them.

Does anyone know how could I go about checking whether a hexagon is clicked without over complicating the whole thing?


texts: How to ease toward a rotation limit, instead of stopping abruptly?

texts:
I rotate my camera using a framerate-independent exponential ease-out blend like so:

    _x += Input.GetAxis("Mouse X") * xSpeed;
    float target = 0f; //I want to blend towards 0
    float sharpness = 0.05f; //the smaller this value, the longer it takes to settle down to the target value
    float referenceFramerate = 90f;//the approximate framerate on my developer machine
    float blend = 1f - Mathf.Pow(1f - sharpness, Time.deltaTime * referenceFramerate);
    _x = Mathf.Lerp(_x, target, blend);

This works fine.

Now my camera should be clipped at a certain rotation yaw.

The new camera rotation yaw is calculated like this:

    _CurrentYaw += _x * Mathf.Abs(_CameraDefaultPos.z);
    if (_CurrentYaw > 160f)
    {
       _CurrentYaw = 160f;
    }
    else if (_CurrentYaw < -120f)
    {
       _CurrentYaw = -120f;
    }

This clipping part of my code makes the camera stop abruptly at the maximum.

How could the above Mathf.Lerp function be adopted to make it so that the _x value would be damped more quickly when going towards the rotation limit?


texts: How can I draw a circle around a specific object, not necessarily the object the script is attached to?

texts:
I have this script that draws a circle around the object the script is attached to.
I would like also to use the centerObject variable as an option to draw another circle around the centerObject, or just only around the centerObject and not the transform the script is attached to. I'm not sure how to do it.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[ExecuteAlways]
[RequireComponent(typeof(UnityEngine.LineRenderer))]
public class DrawCircle : MonoBehaviour
{
    public GameObject centerObject;
    [Range(1, 50)] public int segments = 50;
    [Range(1, 500)] public float xRadius = 5;
    [Range(1, 500)] public float yRadius = 5;
    [Range(0.1f, 5)] public float width = 0.1f;
    [Range(0, 100)] public float height = 0;
    public bool controlBothXradiusYradius = false;
    public bool draw = true;

    [SerializeField] private LayerMask targetLayers;
    [SerializeField] private LineRenderer line;

    private void Start()
    {
        if (!line) line = GetComponent<LineRenderer>();

        if (draw)
            CreatePoints();
    }

    private void Update()
    {
        if (Physics.CheckSphere(transform.position, xRadius, targetLayers))
        {
            Debug.Log("player detected");
        }
        else
        {
            Debug.Log("player NOT detected");
        }
    }

    public void CreatePoints()
    {
        line.enabled = true;
        line.widthMultiplier = width;
        line.useWorldSpace = false;
        line.widthMultiplier = width;
        line.positionCount = segments + 1;

        float x;
        float y;

        var angle = 20f;
        var points = new Vector3[segments + 1];
        for (int i = 0; i < segments + 1; i++)
        {
            x = Mathf.Sin(Mathf.Deg2Rad * angle) * xRadius;
            y = Mathf.Cos(Mathf.Deg2Rad * angle) * yRadius;

            points[i] = new Vector3(x, height, y);

            angle += (380f / segments);
        }

        // it's way more efficient to do this in one go!
        line.SetPositions(points);
    }

#if UNITY_EDITOR
    private float prevXRadius, prevYRadius;
    private int prevSegments;
    private float prevWidth;
    private float prevHeight;

    private void OnValidate()
    {
        // Can't set up our line if the user hasn't connected it yet.
        if (!line) line = GetComponent<LineRenderer>();
        if (!line) return;

        if (!draw)
        {
            // instead simply disable the component
            line.enabled = false;
        }
        else
        {
            // Otherwise re-enable the component
            // This will simply re-use the previously created points
            line.enabled = true;

            if (xRadius != prevXRadius || yRadius != prevYRadius || segments != prevSegments || width != prevWidth || height != prevHeight)
            {
                CreatePoints();

                // Cache our most recently used values.
                prevXRadius = xRadius;
                prevYRadius = yRadius;
                prevSegments = segments;
                prevWidth = width;
                prevHeight = height;
            }

            if (controlBothXradiusYradius)
            {
                yRadius = xRadius;
            }
        }
    }
#endif
}


texts: What is the difference between a Viewport and a Scissor Rectangle?

texts:
In XNA, what is the difference between a Viewport and a Scissor Rectangle, and when should I use each one?

It looks like viewport clipping is applied to the geometry before the rasterization state, which should make it "faster", while the scissor test is applied afterwards during the pixel stage.

I primarily work with 2D graphics, and from what I can tell, they both seem to function the exact same way with no appreciable difference otherwise, save that the scissor test is more annoying to set up, because you have to create a new RasterizerState object to enable it.


texts: maya root motion animation jumps back and forth in Unity

texts:
I have a custom made model from Maya that is supposed to have root motion.
But when I put the animation into the animator in Unity it keeps jumping back.
I have configured the model in Unity as Root motion. So now I don't know whether it's a problem with the model in Maya or the setup in Unity. I have compared my Unity setup to a Jose Diaz Toon Dinosaur setup which seems to be the same so I am suspecting that there is a problem with the model export from Maya.


texts: why child class can access object while parent can't

texts:
I have Block class which is the parent and StandardBlock the child , the prefab block have StandardBlock script attached to it, and according to my small knowledge in inheriting I though this would work

public class Block : MonoBehaviour
{
HUD HUDscript;
// Start is called before the first frame update
void Start()
{
    HUDscript = GameObject.FindWithTag("Canvas").GetComponent<HUD>();
}
public void OnCollisionEnter2D(Collision2D col)
{
    HUDscript.addPoints();
    Destroy(gameObject);
}
}

and child class

public class StandardBlock : Block
 {

      // some code
}

but this is the error that i got

NullReferenceException: Object reference not set to an instance of an object
Block.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Scripts/Gameplay/Block.cs:24)

while writing OnCollisionEnter2D in the child class worked fine


texts: Focus scene2d UI actors programmatically in libGDX

texts:
I am trying to implement keyboard movement in game main menu which is libGDX Stage with UI-Actors. I'm also trying to code this feature myself since I can't neither find anything relevant to it in the docs nor find libraries for the feature.

I have a bunch of Buttons in the VerticalGroup. Using keyboard UP and DOWN keys, I want to somehow focus, highlight or hover buttons like the way that mouse hovering do. Hovewer, firing FocusEvent on children of the VerticalGroup do not change Button appearance.

So how do I focus these buttons or any other UI element (because there are other menus with more complex UI architecture) ?

Here is the code for the menu (Kotlin, using ktx-scene2d builders and ktx-actors event methods):

class MainMenuUi: Stage() {
    val root = verticalGroup {
        center()
        setFillParent(true)
        expand(true)
        space(spacing)
        fill(0.5f)
        wrap(false)

        textButton("Start")
        textButton("Settings")
        textButton("Exit")

        onKeyUp { key ->
            when(key) {
                Input.Keys.UP -> { /* ??? */ }
                Input.Keys.DOWN -> { /* ??? */ }
            }
        }
    }.also {
        addActor(it)
        keyboardFocus = it
    }
}


texts:
The game I'm working on is based on different levels. I can use different activities or only one activity with different layouts ( or maybe only one layout, you have to apologize me but I'm studying alone and it's pretty hard to learn alone ).

My problem is: I'm not sure what is best way to implement levels in game. If I use only one activity as container for each level, where I design each level as different layout, how can I refresh my current activity with the new content ?
To make it clear, think about "Cut the rope", is every level a different activity or they load different xml's on the same ?

I'm sorry if this question is not properly written, but I can't find more specific terms to make it better.


texts:
I have some ads that take a very long time to load. I was wondering it it is possible to have them load while the use was in the splash screen. I have looked at this answer:

https://stackoverflow.com/questions/5133342/how-can-i-make-my-ads-appear-faster-in-my-android-app

And the answer suggests to use a splash screen to load the ads. How can I figure out when the ads are loaded, to continue to my next activity? What will happen if the user is on airplane mode, will it get stuck in the splash screen? I have seen the admob add listener, but that needs the adview, but my adview is in the next activity? How should I tackle this problem?

Also, when I try to do this:

 AdView.setAdListener(new AdListener() {
     // Implement AdListener
 });

I get:

Non-static method cannot be referenced from a static context. The thing is, I am trying to see when the add which is in the next activity is done loading.


texts: Need help with getting a direction vector between two given points

texts:
I need to find the angle of rotation from a bullet traveling from point A to point B, like in my attached diagram. I tried searching, but I got a little lost in which exact formula to use.

I want to find the direction of a bullet, expressed as a vector with X and Y coordinates.


texts:
We are a small software company trying our hand at our second game. Since our first games' process was a living nightmare (since we used webdevelopment workflow) I have decided to educate myself on how to manage a game project on a high level.

How does your process work, from idea to launch? Preferably in situations where you have a team that needs to cooperate.

I've seen these 2 links, which are useful in a way, but was wondering if there are better/more comprehensive ways to do this?

http://www.goodcontroller.com/blog/?p=136

http://gogogic.wordpress.com/2009/02/09/symbol6-how-we-created-an-iphone-game/

All input would be infinitely appreciated.


texts:
I'd like to know are there some international fonts?

I mean a font for all European languages including Russia.

The question is about XNA fonts.


texts: ID3D11Device::CreateInputLayout: Encoded Signature size doesn't match specified size

texts:
I get [ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE] with the following code:

// Vertex data
struct VertexData {
    XMFLOAT3 v;
    XMFLOAT2 vt;
    XMFLOAT3 vn;
};

// ...

// Create the input layout vertex shader.
D3D11_INPUT_ELEMENT_DESC vertexLayoutDesc[] =
{
    { "V", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexData, v), D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "VT", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(VertexData, vt), D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "VN", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexData, vn), D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

HRESULT hr = g_d3dDevice->CreateInputLayout(vertexLayoutDesc, _countof(vertexLayoutDesc), geomVertexShaderBlob->GetBufferPointer(), geomPixelShaderBlob->GetBufferSize(), &g_d3dInputLayout);

And wannabe matching HLSL code:

struct Input
{
    float3 v : V;
    float2 vt : VT;
    float3 vn : VN;
};

struct Output
{
    float4 color : COLOR;
    float4 position : SV_POSITION;
};

Output main(Input input) {...}

I can't spot the mismatch and what exactly the error message is pointing to. Weird thing I have very similar input layout and shaders that work perfectly fine, but this one doesn't.


texts: 2-Color Fonts in Unity? (so maybe called 3-Color including transparent alpha?)

texts:
I have been trying to make my game title screen look better. I realised it was because all my fonts have just one colour.
I read some very old threads about a Editor Scripts to extract the font to png format. I then see there is now a way to do it in the 'hamburger' menu of the Font in Inspector.
I had to change my font to be not 'Dynamic' then it allowed me to extract a copy to PNG. I opened this in GIMP and added my white inside the outlines of each character (it had been alpha before this, giving a horrible see-thru effect on the letters).
I put this back into Unity (the new PNG) and used it as the source texture for my Text Shader. However it is still not handling both colours. (Screenshot below). So what can I do using Unity 2020 to achieve better looking text? I've read this: (https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/StyledText.html) and many other pages on Unity site but I am now going around in circles not achieving anything.
Thanks for any help.

EDIT: Since DMGregorys comment. I am posting picture of my import settings on the modified (coloured-in) font PNG file:

EDIT 2: The 3rd screenshot shows the 'Text' objects settings. Note I have changed Material to be my extracted one. 4th screenshot shows that Material's settings
enter image description here


texts: Important aspects to consider while making a technical design document

texts:
I'm working on a open world strategy game for which I'm planning to make technical design documentation.

How do we decide exactly what we need to include to ensure the design document is as complete as it can be?


texts:
I've read that application.loadLeveAdditiveAsync is a pro only feature. I'm looking for an asset that can do something similar. I would like to load assets based on the camera/player position. Ideally, it would be great to dispense with scenes entirely and just load information based on some distance value. This asset seems to be doing just that: https://www.assetstore.unity3d.com/en/#!/content/8015 however I'm not sure if the author is active anymore, and recent customers are complaining about a serious bug.

Any recommendations about assets that allow for seamless, open world style transitions between scenes would be great. (using Unity 3D 5, basic version, and writing in c#).


texts: OnCollisionEnter is called over and over again

texts:
Currently I'm trying to let the player place a GameObject in the world. You can imagine this like a RTS game where you can place a building you have just build.
My problem now is, in order to avoid that the new GameObject intersects with another I check for collisions. For this my GameObjects have a BoxCollider (MeshCollider did not work) and a non kinematic RigidBody.
The first tests looked promising but now I'm facing a problem I can't quite explain: Sometimes, but not always OnCollisionEnter and OnCollisionExit are called over and over again, even when both objects are not moving. They overlap and stay that way. I had guessed that they always only get called once.
My Unity version is 5.3.0f4.

Further information: Each of my GameObjects have a guid so I can identify. They get generated when the GameOject is created.
The debug output in OnCollisionEnter and Exit look like this:

  OnCollisionEnter from 593b209f-cc63-4d31-9911-34c5f69ac224
  Collided with: 77e05881-2adb-459d-a134-8205cf4e3327
  OnCollisionEnter from 77e05881-2adb-459d-a134-8205cf4e3327!
  Collided with: 593b209f-cc63-4d31-9911-34c5f69ac224
  OnCollisionExit from 593b209f-cc63-4d31-9911-34c5f69ac224!
  OnCollisionExit from 77e05881-2adb-459d-a134-8205cf4e3327!

And then the same output again.

I'm happy for any hints and help. :)


texts:
Can anyone tell me if there is a async version of LoadImage() method? I found about Resources.LoadAsync, however the method doesnt work.

Thank you


texts: How can I separate gameview from UI most efficiently in Unity?

texts: Let me provide an image to illustrate what I mean. It is from a game called Runescape.


texts: LibBDX create a tail when the object is moved

texts: I am looking for a way to implement in my game a kind of shadow/tail which will be displayed after the object is moved. Should I use animation? If yes how? Here an example:


texts: what is use of ScriptableSingleton in Unity?

texts:
in unity 2020.x Unity just has introduced scriptable Singleton. a class that derives from Generic Class Called ScriptableSingleton its like singleton but you only can have single instance of it and seems to be good for ScriptableObjects that need to be Forced to be Single. but there are some differences.
they can be project Specific or Shared. they can get any format and unlike usual scriptableObjects they have no visualization in the inspector. the question is how should i use them and they are appropriate for which approaches? this is the link to the reference:
https://docs.unity3d.com/2020.1/Documentation/ScriptReference/ScriptableSingleton_1.html


texts: Entity Component System - Handling Input

texts:
I'm developing a using the Entity-Component model, and so far have components for position, input, graphics and a camera, and systems for rendering graphics and handling input.

All seems to be working well, and I can use my model to create a multi-player, multi-camera setup relatively easily.

Anyway, my problem is that my input system checks keypresses against each player's controls, but I'm not sure how to react to these keypresses without introducing a lot of coupling.

For example, if 'W' is pressed, I want to tell player 1 to move upwards, but that first involves some collision detection -- something I'm not sure my input system should handle.

Advice greatly appreciated!

Thanks in advance,
Rich.


texts: How can I tell what a rectangle intersects with?

texts:
I understand XNA's Rectangle class is rather limited, but surely there is a way to tell what a Rectangle is intersecting with?

If I had Rectangle boundingBox = new Rectangle(stuff here); how would I retrieve what is currently (if there is anything) intersecting boundingBox? Is there any easy method to detect if anything is intersecting it instead of testing with two individual rectangles with boundingBox.intersects()? Similarly, if this is possible, how would I retrieve what rectangle it is colliding with?

If there isn't any easy way of doing it, how would you go about implementing this if you had loads of possible rectangles you want to hit-test?


texts: How does one multiply by a constant in a VS1.1 assembly vertex shader?

texts:
I'd like to multiply a vector by -1

e.g.

mul    r0,    r0,    -1

When I try this, I get this error message:

SimpleShaderA.vsh(20,17): error X2000: syntax error : unexpected integer '1l'

How can I specify -1 in my (first) shader program?


texts: UObjectFinder versus UClassFinder; when is one better than the other?

texts:
I want to change the default pawn of my game and I decided to do it with c++.

I came up with this solution, which works fine:

static ConstructorHelpers::FClassFinder<APawn> MyPawn(TEXT(" address..."));
        DefaultPawnClass=Pawn.Class;

However, I searched on the internet and found this approach used more often:

static ConstructorHelpers::FObjectFinder<UClass> MyPawn(TEXT(" address..."));
        DefaultPawnClass=(UClass*)Pawn.Object;

What advantages does UObjectFinder have over UClassFinder?

Are there certain circumstances where one is preferable to the other?


texts:
I've been following this Pong tutorial, which is great: https://noobtuts.com/unity/2d-pong-game. The C#, unity components etc I understand. But what I am having trouble with is understanding the logic of how it reverses the direction of the ball depending on where it hits.

I know that what it is doing is condensing a new Y value to -1, 0, 1, via the hitFactor function, which returns that value and then sets that to the new Y (so going up or down) based on the relative ball position to the paddle, divided by the height/size of the paddle. But that's the bit I don't really truly understand, how does that work and why? I have been using Debug.log to send all the different parts of it to try and understand, as well as visually looking in Unity and trying to figure it out from there via the inspector, but I'm just having a mental block. To me I can vaguely see how this code is finding a relative position and then dividing by the height of the paddle to somehow condense it to this range but I'm really just stuck on it in my head.(the hitfactor function itself is basically where I am stuck)

Here's the function:

float hitFactor(Vector2 ballPos, Vector2 racketPos,
            float racketHeight) {
// ascii art:
// ||  1 <- at the top of the racket
// ||
// ||  0 <- at the middle of the racket
// ||
// || -1 <- at the bottom of the racket
return (ballPos.y - racketPos.y) / racketHeight;
}

And in context with the collision:

if (col.gameObject.name == "RacketLeft") {
    // Calculate hit Factor
    float y = hitFactor(transform.position,
                        col.transform.position,
                        col.collider.bounds.size.y);

    // Calculate direction, make length=1 via .normalized
    Vector2 dir = new Vector2(1, y).normalized;

    // Set Velocity with dir * speed
    GetComponent<Rigidbody2D>().velocity = dir * speed;

I'm sure this is a very basic thing, but I am struggling with this type of thing. I am on Khan academy, starting from very basic stuff and working my way up, so no doubt maybe when I get to vectors I might understand this more, but I'd like to try and really get my head around this particular issue.

Sorry for the very basic question, I have been dabbling in C# and Unity for a while, but I have realised my weakness is really in the basic core logic of some things....I am a composer by day but I really enjoy trying to get back into this side of my brain, I guess it's super dusty in there hahaha.

Thanks so much in advance for any help, I truly appreciate it.


texts: GLSL - Signed Distance Field vs normal Loop

texts:
I am fairly new in GLSL and only recently discover Signed Distance Field. I am trying to figure out how SDF can perform so well when you use mod() function to repeat but badly when you use for loop function.
I got a feeling that in for loop function, the ray marching is repeat as many times as the loop itself, but when using mod(), it only perform once. Can somebody explain in more detail how this works?

UPDATE1:

This is the mod() function:

float map( vec3 p )
{
    p.x=mod(p.x+3.0,6.0)-3.0;
    p.y=mod(p.y+3.0,6.0)-3.0;
    p.z=mod(p.z+3.0,6.0)-3.0;
    return box( p, vec3(1.,1.,1.) );
}

and Here is the for() loop function:

float map( vec3 p )
{
    p.yz = rotate(p.yz, mouse.y*10.);

    float b = box( p, vec3(1.,1.,1.) );
    float aa = b;

    for(int i=0; i<5; i++)
    {
    float off = float(i);
    vec3 q = p+off*.5;
    q.xz = rotate(q.xz, -mouse.x*off*12.);
    float c = box( q, vec3(off,1.,1.) );
    aa = fOpUnionRound(aa,c,.5);
    }
    return aa;
}


texts: How do client-server cooperation based games like Diablo 3 work?

texts:
Diablo 3 cooperates with Blizzard servers even during single player games. In fact, Blizzard has had problems with the games "melting their servers."

I would like to ask: How do the client and the server communicate? What details does the client leave to the server, and vice versa? What details are redundant - both the client and the server know - and how often do they disagree?

The previous paragraph contains the important questions, but I have a few more that I must explain my motivation towards. I am interested in the programming of botting. Ethical botting - I don't plan on actually abusing the automation to run 24/7. I just find it to be a great programming challenge to glean information from a game, and then make decisions from that information. I am stuck in the starting gate. The unofficial questions from this post would be: How can I make a bot (language, tools, libraries)? Can I get information through the communication between client and server, rather than the brute force pixel detection easily used in more static games?

There probably is a trust issue, and to that all I can say is that I promise not to abuse the answers. But please feel free to answer any of the questions you feel comfortable with. Thank you!


texts: Strings and Variables Inheritance From Another Class in Java

texts:
I am working on a program and I want these variables and strings, to be called on another class. So I have these:

    public static boolean newgame = false;
/*
 * Declares Character Status
 */
public boolean male = false;
public boolean female = false;
public static String charactername;
public static String characterclass;
public static int hp = 100;
public static int mp = 100;
public static int charstr = 5;
public static int chardef = 5;
public static int charagi = 5;
public static int chararank;
public static int charaprofile;
public static double criticalhit = 0.0;
public static double luck = 0.0;

/*
 * Determines how each classes time fighting.
 */
public static int timeFightSlow[] = {4000, 4500, 4800, 5000};
public static int timeFightMedium[] = {2000, 2500, 2700, 2860,3000};
public static int timeFightQuick[] = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

/*
 * Declares Items:
 */
public static String gender;
/*
 * Declares Classes
 */

public static String sf = "Swordsman";
public static String sm = "Sword Mystic";
public static String warrior = "Warrior";
public static String duelist = "Duelist";
public static String lancer = "Lancer";

/*
 *
 */
public static int experience = 0;
public static int iniexp = 100;
public static double totalexp = iniexp*2.5;
public static int initialhp = 100;
public static int hptotal = initialhp+10;
public static int initialmp = 50;
public static int mptotal = initialmp*2;

The problem I get is how can I call them up on a new class? Can I call them again or I should make another integer for those?


texts: How To show document directory save image in thumbnail in cocos2d class

texts:
I have just implemented multiple photo selection from iphone photo library and i am saving all selected photo in document directory every time as a array, now i want to show all saved images in my class from document directory as a thumbnail, i have tried some logic but my game getting crashing, My code is below. Any help will be appreciate. Thanks in advance.

-(id) init
{
    // always call "super" init
    // Apple recommends to re-assign "self" with the "super" return value

    if( (self=[super init])) {

        CCSprite *photoalbumbg = [CCSprite spriteWithFile:@"photoalbumbg.png"];
        photoalbumbg.anchorPoint = ccp(0,0);
        [self addChild:photoalbumbg z:0];

        //Background Sound
    //    [[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"Background Music.wav" loop:YES];

        CCSprite *photoalbumframe = [CCSprite spriteWithFile:@"photoalbumframe.png"];
        photoalbumframe.position = ccp(160,240);
        [self addChild:photoalbumframe z:2];

        CCSprite *frame = [CCSprite spriteWithFile:@"Photo-Frames.png"];
        frame.position = ccp(160,270);
        [self addChild:frame z:1];

        /*_____________________________________________________________________________________*/

        CCMenuItemImage * upgradebtn = [CCMenuItemImage itemFromNormalImage:@"AlbumUpgrade.png"
                                                              selectedImage:@"AlbumUpgrade.png"

                                                                     target:self
                                                                   selector:@selector(Upgrade:)];
        CCMenu * fMenu = [CCMenu menuWithItems:upgradebtn,nil];
        fMenu.position = ccp(200,110);
        [self addChild:fMenu z:3];

        NSError *error;
        NSFileManager *fM = [NSFileManager defaultManager];
        NSString *documentsDirectory = [NSHomeDirectory()
                                        stringByAppendingPathComponent:@"Documents"];
        NSLog(@"Documents directory: %@",
              [fM contentsOfDirectoryAtPath:documentsDirectory error:&error]);

     NSArray *allfiles = [fM contentsOfDirectoryAtPath :documentsDirectory error:&error];

        directoryList = [[NSMutableArray alloc] init];

        for(NSString *file in allfiles) {
            NSString *path = [documentsDirectory stringByAppendingPathComponent:file];
                [directoryList addObject:file];

        }

        NSLog(@"array file name value ==== %@", directoryList);

        CCSprite *temp = [CCSprite spriteWithFile:[directoryList objectAtIndex:0]];
        [temp setTextureRect:CGRectMake(160.0f, 240.0f, 50,50)];
       // temp.anchorPoint = ccp(0,0);

        [self addChild:temp z:10];
        for(UIImage *file in directoryList) {

//             NSData *pngData = [NSData dataWithContentsOfFile:file];
//        image = [UIImage imageWithData:pngData];
        NSLog(@"uiimage = %@",image);
        //  UIImage *image = [UIImage imageWithContentsOfFile:file];
        for (int i=1; i<=3; i++) {
            for (int j=1;j<=3; j++) {
                CCTexture2D *tex = [[[CCTexture2D alloc] initWithImage:file] autorelease];

                CCSprite *selectedimage = [CCSprite spriteWithTexture:tex
                                                                 rect:CGRectMake(0, 0, 67, 66)];
                selectedimage.position = ccp(100*i,350*j);
                [self addChild:selectedimage];
            }
        }
         }

    }

    return self;
}


texts: What methods should save/load a game state

texts:
There are a lot of articles about how to save a state of a game and they are pretty good. But I have one conceptual misunderstanding where should I save the state?

My game has number of screens and pair of them are MainMenuScreen and MainSceneScreen these are inherited from Screen class. MainMenuScreen is shown at start of the game the MainSceneScreen little later.

What is the problem? I navigated to MainSceneScreen, forced Android to stop the application (I change a language settings on the device to achieve it, please let me know if I'm wrong). After that I select the application again and I can see MainMenuScreen is shown. But I want MainSceneScreen to be shown.

I suppose I should override resume method. But what class I should override? I have class PsGame that extends Game class of libgdx. I put breakpoints to its resume method and  it turned out that method was not called. I investigated the problem and I've found little strange code in onResume method of  AndroidApplication class of libgdx:

    if (!firstResume)
        graphics.resume();
    else
        firstResume = false;

My debugger said firstResume was true and didn't go to *graphics.resume()*line.

Sorry for a lot of words but could you answer following question:

What did I do wrong?
What methods should I override?

Thank you in advance.


texts: 3D models on 2D background perspective mismatch

texts:
we are working on a tactics game, with a hand drawn 2D backgrounds and 3D models moving on them. The game generates a 2D grid placed on a XY plane, with faux isometric tiles (Diamond Grid).

I have tried following the guides found here to create the "isometric" effect on the 3D models: prepared two ortho cameras, one perpendicular to the 2D elements and seeing only them and another rotated (30,45,0) which sees only 3D models. Like this:

The issue we're having is the mismatch of the positions between the elements seen by the cameras.

Character should be standing on the tile with the green border. This cannot be solved by simply moving the 3D camera to match these positions because the seem to differ for objects placed in different parts of the screen.

Could anyone please help?

Thanks!


texts: How do I merge colliders in a tile-based game?

texts:
I'm doing a tiled based platformer in unity, and I was having some issues with collisions and I figured the problem was the way my colliders were arranged.

So right now, my collision look like this:

You see each tile has its own collider, outlined in black. Polygon colliders in unity are formed by lists of points in space, and I can manipulate them freely.
What I would ultimately want, is to have all this colliders in the example image to merge into just two colliders ( or maybe one, depending on how the edges of those squares touching would be handled ):

How could I achieve that? Is there any known algorithm?


texts: What are ways I can transition from enterprise application development into gaming development?

texts:
I'm currently a software architect using the Microsoft stack of enterprise app development tools (.NET, C#, SQL Server, etc.). I've been thinking about transitioning over to game dev.

What paradigms exist in gaming that
don't in enterprise development that
I'd need to learn? I'm deeply versed
in DB design, design patterns, theory
etc. Will this help me?
Overall, will
it be like I'm starting over from
scratch in changing careers?


texts: How to create a map array with multiple layers?


texts:
I am using Unity. I have created eight different types of objects, stored in an array, and I am displaying them on the scene in a grid pattern with random order.

The first four objects in the array are red. The player needs to destroy all four red objects to go to the next level.

The code I've writted so far uses the Random.Range method, which chooses objects completely randomly. Sometimes it generates a grid that doesn't contain four red objects, so my player can't destroy them and proceed to the next level.

How do I randomly generate this grid so that it is guaranteed to have exactly four red objects?

Here is my code.

public int gridWidth = 0;
public int gridHeight = 0;
public GameObject[] facePrefab = new GameObject[8];

void Awake()
{
    gridHeight = Random.Range (3, 5);
    CreateGrid(gridWidth,gridHeight);
}
void CreateGrid(int numX, int numY)
{
    for (int x = 0; x < gridHeight; x++) {
        for (int y = 0; y < gridWidth; y++) {
            GameObject go = Instantiate (facePrefab[Random.Range(0,facePrefab.Length)]) as GameObject;
        }
    }
}


texts:
I just want to change the intensity of a light.

The script is already in the light object, but I can't turn it up or down to save my life, and wherever I look, no one has the answer.

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

public class Flashlight : MonoBehaviour
{

    public bool flashOn;

    void Update()
    {
        if (flashOn)
        {
            light.intensity = 0;

            if (Input.GetKey("q"))
            {
                flashOn = false;
            }
        }
        else
        {
            light.intensity = 1;

            if (Input.GetKey("q"))
            {
                flashOn = true;
            }
        }
    }
}


texts: Full screen shader causes performance hit

texts:
I basically want to have a shader run that can do something like toon shading, or grayscale the whole screen, or radial lighting.

To do this, I create a new bitmap each time the display resizes that is the size of the screen. I then use this as my drawing buffer.

I realized this creates quite a performance hit. Especially on my laptop. Is there a way to do something like this without such a performance hit?

The framework I'm using is Allegro5. This is my current implementation:

void GraphicsContext::flipDisplay()
{
    if(!m_backBuffer)
    {
        al_flip_display();
    }
    else
    {

        setTargetToBackbuffer();
        if(m_shader)
        {
            m_shader->use();
            m_shader->setSampler(m_backBuffer,"tex");
        }
        drawSprite(m_backBuffer,0,0,0);
        if(m_shader)
        {
            m_shader->stop();
        }

        al_flip_display();
        clear();
        setTargetToBuffer();

    }

}

This way all drawing gets drawn to my bitmap, then that bitmap is blitted to the backbuffer.

I tried using single buffering display but it did not help.

Any advice for fullscreen effects?
I have a game I play on my laptop that uses fullscreen film grain and it does not lag. I wonder what they do.

I know that the default shader I set gets ran through every bitmap, but I do not think I can do lighting effects this way since I cannot know which pixel on the screen I'm on.


texts:
I am trying a complete my method, which crops Maya-Animations (from Maya-Models) to specific ones using the SkinnedModelProcessor.

My only problem is, that after one animation-loop completes, the model stays in its last position for about 2-3 seconds until he catches up to the run-cycle again.

My goal is to get rid of that freeze time.
I want to loop it seamlessly.

Here is what I wrote:

public AnimationClip getCurrentAnimation(string clipName, string cropName, float blendTime, int beginFrame, int endFrame, int totalFrames)
{
    //The new list which only has the specific keyframes
    List<Keyframe> region = new List<Keyframe>();

    //The original clip "Take 001" from Maya, which has every
    //animation in one timeline
    AnimationClip clip = _skinningData.AnimationClips[clipName];

    //The new duration of the cropped clip
    int duration = 0;

    //Since XNA makes 7502 frames out of 21, I have to
    //calc the region-keyframes to proper numbers
    if (endFrame == 0)
        endFrame = clip.Keyframes.Count;
    else
        endFrame = ((endFrame * clip.Keyframes.Count) / totalFrames);

        beginFrame = ((beginFrame * clip.Keyframes.Count) / totalFrames);

    //Start to sort out
        for (int i = beginFrame; i < endFrame; i += 1)
        {
           Keyframe k = clip.Keyframes[i];

           //Add duration of 16 (60fps) to overall-length
           //of animation, if this keyframe does some "real"
           //transformation, instead of being a static keyframe of XNA
           if (k.Time.Milliseconds > duration)
                duration += 16;

            k.Time = TimeSpan.FromMilliseconds(duration);
            region.Add(k);
         }

         AnimationClip cropped = new AnimationClip(cropName, TimeSpan.FromMilliseconds(duration), region);
         return cropped;
}


texts: Clearing an SFML scene with a partially transparent color

texts:
Is there way to clear a scene with a transparency (alpha) value, in pure SFML?

I'm trying to clear with rgba(0,0,0,128) so the previous frame still partially shows through, which would create a motion blur effect.

I tried window->clear(Color(0,0,0,128)); but with no result


texts: How to use Java 8 with Lib GDX in IntelliJ?

texts: I have set the jdk to Java 8 and I have modified all the build.gradle files in my project to have sourceCompatibility = 1.8 instead of 1.6. My problem is that while it does work on Desktop it doesn't when I run it on Android. Can someone tell me how to properly set up the project to use Java 8 so that it works on all platforms in IntelliJ?


texts:
Hi everybody I am making small game using  pure Java 8 and rednering it by Java AWT Graphics2D method . My question  is how to make that user can change the quality of game. For example: 720p, 1080p, 1440p. Something similar that is when playing YouTube video.
The steps I will make?

Make 3 pictures of each, each with different quality.
Then load them.

Is this the right way?
But Java is default only 72dpi so each of them will be the same quality. So how to render it in different resolution?
Thanks in advance,
Maratonec
Edit:
I will be using LibGDX for rendering. So I will be using OpenGL.
But still don’t know how to make in LibGDX.
Edit:
So I now understand that using LibGDX mipmap I will make my scaling nicer. So I will have 1440p image and scale it up down? Or I will have to have each image for each resolution (720p, 1080p,1440p) and they will change to user selected resolution and only scaling to the window size?
The second method I have in mind how to do, but for second I need code example.
Thanks one more time for spending time with beginner!


texts:
I'm developing a game in Java for Android, using LibGDX.
In my render(), between the batch.begin() and batch.end() I'm running through all the game objects and draw them.

Every game object is stored in a list, which that list is stored inside a hash map. I iterate through this hash map, getting every list and going through that list, like this:

    batch.begin();
    Iterator it = objectsMap.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        Array list = (Array) pair.getValue();
        for (int i = 0; i < list.size; i++) {
            GameObject object = (GameObject) list.get(i);
            drawObject(object);
        }
    }
    batch.end();

My drawObject() code:

private void drawObject(GameObject object, float x, float y) {
    if (object == null) {
        return;
    }
    if (object.getVisibility()) {
        TextureAtlas.AtlasRegion currentFrame = object.getCurrentFrame();
        if (currentFrame != null) {
            float objectAlpha = object.getAlpha();
            Color color = batch.getColor();
            if (objectAlpha != 1) {
                color.a = object.getAlpha();
                batch.setColor(color);
            }
            batch.draw(currentFrame, x - object.getOriginX(), y - object.getOriginY(), object.getOriginX(), object.getOriginY(), currentFrame.getRegionWidth(), currentFrame.getRegionHeight(), object.scaleX, object.scaleY, object.getSpriteDirection());
            color.a = 1;
            batch.setColor(color);
        }
    }
}

A method called setRegion() sets the current animation frames of the object:

protected void setRegion(String name, float frameDuration) {
    currentFrame = atlas.findRegion(name, 0);
    if (currentFrame == null) {
        currentFrame = atlas.findRegion(name, -1);
    }
    width = currentFrame.getRegionWidth();
    height = currentFrame.getRegionHeight();
    animationStateTime = 0;
    animation = new Animation(frameDuration, atlas.findRegions(name),      Animation.PlayMode.LOOP);
}

And in the update() of the objects this is called:

            currentFrame = (TextureAtlas.AtlasRegion) animation.getKeyFrame(animationStateTime, isLooping);

The getCurrentFrame() method only returns currentFrame variable.
The alpha is a field with a value between 0 and 1. (getAlpha() returns only the field)

My question is that considered a "heavy" activity? Can this be a significant impact on the FPS values? Because I'm running my game on old devices (like Galaxy S2) and the FPS can get pretty low values. I'm trying to find the cause to it.
I used to have a reference to every list but with the time I realized I'm going to have too much lists, so I decided to do it like this. Maybe you know a better way of holding references to all game objects?

Thanks!


texts: How to convert pixel coordinates to GL coordinates in 2D space?

texts:
I know that if you want to display a sprite on screen (in 2D) you can use glOrtho and essentially make 1 gl unit equal to 1 pixel, so when I plot out the vertices for say a 128x128 image (on a quad), I can define the vertices as -64/64, -64-64, etc and then when I map my texture coords to that quad, the image is displayed at a 1:1 ratio.

However, lets say I wanted to not use glOrtho and wanted to have a perspective view, so I can combine 2D sprites with 3D models and whatnot? I'm at a loss on how to convert/set up the coordinates for the planes/quads I want to draw images to, in a way that will match the resolution of the image. That is, define coordinates or convert them in such a way so that when a 2D sprite is right at the near plane, that sprite is mapped as 128x128 pixels on the screen.


texts:
I want to write a game in which the player shoots projectiles (bullets, etc).
Since I don't know how many and when these projectiles will be shot, I wonder how to buffer and render them (and when!).

Normal opengl pipeline (as I understand it):

Create and bind buffers (once)
Buffer data to these buffers (once)
In loop - Draw every frame/period.

What about temporary objects ? I buffer them only when used ? I suppose I get the player input as trigger, and then buffer them and draw them. Is this approach fast enough ?

Thank you


texts: Why bother with a separate normal matrix, if there is never non-uniform scaling on the view matrix?

texts:
I am updating one of my shaders to a version of OpenGL/GLSL that doesn't automatically provide gl_NormalMatrix (for educational purposes; I'm not ripping out working code for the sake of it). Therefore, I need to compute my own normal matrix on the CPU and pass it in.

I understand that a separate normal matrix is used to avoid issues with non-uniform scaling affecting the direction of normals. However, I've noticed that in my code I never perform any scaling let alone a non-uniform one. So, I'm tempted to use the upper left 3x3 sub-matrix for transforming my normals and calling it a day (perhaps normalising them to allow for uniform scaling).

My program assumes that every mesh it loads is already at the correct size, with no scaling required.

Will I soon run into something that requires scaling (uniform or otherwise), or is there another reason for using a separate normal matrix that I haven't realised?


texts: Is there a value in unifying animation lengths in turn based game?

texts:
It might be a small detail, but I'm wondering if there is a significant impact on the game feel between scenario where for example all characters in a game have the same attack animation length and scenario where each character may have different attack animation length.

Has there ever been anyone exploring such topic?


texts: Problem when reloading unity scene(level)

texts:
I am using

SceneManager.LoadScene(SceneManager.GetActiveScene().name);

to reload my current scene in unity  , but when i run the game ,in hierarchy lots of scene are appearing. Also if i do some editing, i can not save the scene any more. unity is giving and error "Overwriting the same path as another open scene is not allowed". I am new to game development. I would appreciate any help.


texts: So when you get near to the chunk it splits, and then when getting near to the splited chunk it does the same again and over (quad tree). But what is the formula for calculating the distance when it should split depending on the distance? For smaller chunks, smaller distance?


texts:
Possible Duplicate:
  How do you come up with ideas for new games?

Hello!
I want to ask you about ideas for games, what methods do you know and which you are useing ?
I know for example method, to write a lot of smaller ideas on pieces of paper, and when I have 20-30 then, I try to connect one of them with another, to genereate new idea. For my the most difficult is to extend some idea, do you know some advice for me ?


texts: Can GPU draw from one VB and upload to another VB at the same time? (OpenGL)

texts:
We have a working implementation of vertex double buffering, rendering from one buffer and uploading vertex data to next frame buffer at the same time.

However I am concerned that CPU spends quite a lot of time uploading vertex data. Is the upload blocked by video driver because it's busy with drawing?

Or is it caused by driver's pipeline using the frame N+1 buffers for internal rendering of the frame N-1 frame while the drawing thread is issuing commands for frame N and I should consider switching to triple buffering (however I seriously doubt that it can improve FPS)?

Or should I rather queue the frame N+1 vertex uploads and do them after frame N commands have been issued so that there are no blocks in driver?

It's just that the thread that uploads vertex data also does much other work and is now a bottleneck and I want to offload it as much as possible and definitely don't want to see it blocked by driver.


texts:
I'm using SDL and need to plot pixels one by one on the screen. When I do this, it's extremely slow. I followed the tutorial here:

http://www.programmersranch.com/2014/02/sdl2-pixel-drawing.html

Which basically said to call:

SDL_RenderClear();

SDL_RenderCopy();

SDL_RenderPresent();

SDL_UpdateTexture();

Right after I update my pixel array.

I ran a loop (which calls the above functions) to demonstrate the issue:

for (unsigned int i = 0; i < 128; i++)
    for (unsigned int j = 0; j < 128; j++)
        plot_pixel(j, i, 0xff); // x, y, ARGB val

But it runs painfully slow. Is there a better way to plot pixels with extreme speed? The whole idea of my program is to plot pixels as fast as possible, and it takes several seconds to run through that loop and plot 128*128 pixels.

Here is the code for plot_pixel:

void plot_pixel(int x, int y, int argb)
{
    pixels[y*width+x] = argb;
    SDL_UpdateTexture(texture, NULL, pixels, width * 4);
    SDL_RenderClear(renderer);
    SDL_RenderCopy(renderer, texture, NULL, NULL);
    SDL_RenderPresent(renderer);
}

The code works exactly like I want it to (it plots a pixel) but its painfully slow.


texts: How can I support objects larger than a single tile in a 2D tile engine?

texts:
I´m currently working on a 2D Engine containing an isometric tile map. It´s running quite well but I'm not sure if I´ve chosen the best approach for that kind of engine.
To give you an idea what I´m thinking about right now, let's have a look at a basic object for a tile map and its objects:

public class TileMap {
   public List<MapRow> Rows = new List<MapRow>();
   public int MapWidth = 50;
   public int MapHeight = 50;
}

public class MapRow {
   public List<MapCell> Columns = new List<MapCell>();
}

public class MapCell {
   public int TileID { get; set; }
}

Having those objects it's just possible to assign a tile to a single MapCell. What I want my engine to support is like having groups of MapCells since I would like to add objects to my tile map (e.g. a house with a size of 2x2 tiles). How should I do that? Should I edit my MapCell object that it may has a reference to other related tiles and how can I find an object while clicking on single MapCells? Or should I do another approach using a global container with all objects in it?


texts:
I am currently polishing a digital CCG where people can play against friend and random opponents in a classical Magic the Gathering-like duel CCG.

I plan to award the players with 20 ingame currency units (lets call them gold) for each hour they are playing, 50 for each day they are playing and X for each victory.

Now, the X is what I am trying to calculate here, since I would prefer keeping the currency to a certain value, but also with to entice the players to battle.

I could go with a solid figure, say 25, for beating up an opponent. But that would result in experienced players only beating up newly started players, making the experience lame for both.

I could also make a laddered tier, where you start at level 1, and raise in level as you defeat your opponents, where winning over a player awards you his level x 2 in gold.

Which would you prefer if you were playing a game like this. There is no gold-based scoreboard, but the gold is used to purchase new cards along the way.


texts: How do physics engines like Box2D detect and respond to collisions between arbitrary polygons?

texts: I've always wondered how collision detection like this was achieved, and I've always wondered what the response would be. Do they perform line-line intersection tests for each line making up the two polygons? If it'd make the question any more specific, how does Box2D handle this?


texts: Bullet physics convex hull center of mass

texts:
I am trying to make a convex hull collider for bullet physics. I am using BulletSharp.CompoundShape and BulletSharp.ConvexHullShape.
This is model of a chair in unity with rigidbody and convex mesh collider (how i expect it to behave):

This is that same model in my engine:

Here is the chair in blender:

When attaching collision shapes to CompoundShape there is an option to add offset, i tried setting that offset to center of volume of mesh i calculated, it did not work.
Simple solution would be to center object in blender somewhere around its center of mass, but can this be avoided?
Can i somehow change the chairs center of mass in bullet?
Here is a picture of chairs acting more naturally after changing the center in blender:

All pictures were taken when rigidbodies were still and probably asleep.


texts: Game Physics: Implementing Normal Reaction from ground correctly

texts:
I am implementing a simple side scrolling platform game. I am using the following strategy while coding the physics:

Gravity constantly acts on the character.
When the character is touching the floor, a normal reaction is exerted by the floor.

I face the following problem:

If the character is initially at a height, he acquires velocity in the -Y direction. Thus, when he hits the floor, he falls through even though normal force is being exerted. I could fix this by setting the Y velocity to 0, and placing him above the floor if he has collided with it. But this often leads to the character getting stuck in the floor or bouncing around it. Is there a better approach ?


texts: Are binary storage methods more efficient than text based ones?

texts: I'm working on a game which could potentially generate rather large save files, and so I'd like to find the smallest (most efficient, if you will) method of saving the game's data. I would need to save block types along with entity positions. Would a binary approach generate a smaller file than a text-based one? If so, how do I store the binary data?


texts: How many active shaders at one frame in the game should I typically use? 5 or more like 100?

texts:
How many shaders are usually active, at the same time in one scene, in modern games? I know that multiple shaders are being used, with the games switching between them in each frame, and it's common to draw objects via the shader:

Draw all objects with shader one
Change from shader one to shader two
Draw all objects with shader two

Still, I know it's not as simple, especially with effects like a glow effect for whole scene, render to texture, etc., but I guess we can assume it works that way most of the time, right? The "group by shader" approach is good, because switching shaders is an expensive operation.

From one side, you cannot have too many shaders, because you want to render the scene fast. On the other hand, you need many different shaders (or uber-shader with branches - quite similar) for skin, metal, water etc.

How many (and which) different shaders would the theoretical, modern, third person, 3D detective game for PC (DirectX 11, if it matters) use? It would be 5, 20 or more like 100 active shaders, counting only active, at some "frame X"? I know it's not one number, but I wonder what scale and factors are important, in consideration for a PC game.

In my sample game, I would use about 9-11 per frame (count it as different, small shaders or one uber-shader - doesn't matter now):

Skin shader
Eye shader (not too much? but they are different)
Metal shader
Ground shader
Snow/rain shader (if required)
Water shader (if the water exists in scene)
Glow shader (only when some special effects are involved)
Light emiter shader (street lamps etc.)
Standard shader (for all other, just standard shading)
Standard shader with normal maps
2D shader (for GUI etc.)

Is it "much" or "not many"? Did I forget about some important shaders that I would need?


texts: How to stop the RotateAround function to rotate after Keypress in Unity

texts:
I have a camera follow script and I am rotating the camera with Q and E key to right and left. The Camera is a child of a camHolder object. I came up with this code, which rotates around the player to the right and left, but it's shaking as it tries to keep rotating around the player.

I didn't come up with a solution to stop the RotateAround function, instead I tried setting rotateSpeed to 0 after I let go of the key, but that didn't work either.

public Transform player;
public float smoothSpeed = 0.125f;
public float rotateSpeed;
private Vector3 velocity = Vector3.zero;

[SerializeField]
private Vector3 offset;

[Space]
public Transform camHolder;

void LateUpdate ()
{
    CameraFollowPlayer();
}

void Update()
{
    RotateCamera();
}

void CameraFollowPlayer()
{
    camHolder.position = Vector3.SmoothDamp(transform.position, player.position + offset,
                                             ref velocity, smoothSpeed * Time.deltaTime);
    transform.LookAt(player.position);
}

void RotateCamera()
{
    if(Input.GetKey (KeyCode.E))
    {
        rotateSpeed += 20f;
        if(rotateSpeed >= 20f)
        {
            rotateSpeed = 20f;
        transform.RotateAround(player.position, transform.up, rotateSpeed * Time.deltaTime);
        }
    }
    else
    {
        rotateSpeed = 0f;
    }

    if(Input.GetKey (KeyCode.Q))
    {
        rotateSpeed += 20f;
        if(rotateSpeed >= 20f)
        {
            rotateSpeed = 20f;
            transform.RotateAround(player.position, transform.up, -rotateSpeed * Time.deltaTime);
        }
    }
    else
    {
        rotateSpeed = 0f;
    }
}


texts:
Long ago I found a website with a huge list of different gameplays; around 250 or so. I wanted to go back but right now I cannot find it (I've already spent some time on Google, believe me).

The site had a little picture with a brief explanation, that's all I remember.

I'd appreciate if anyone who rememebers the web site publish the link.

Thanks in advance.


texts: Why isn't this physics code scaling velocities separately?

texts:
I'm working my way through this book and I'm trying to work this code out:

var squaredVelocity = this.velocity.x*this.velocity.x
                    + this.velocity.z*this.velocity.z;

if (squaredVelocity > Player.SPEED*Player.SPEED) {
   var scalar = Player.SPEED / Math.sqrt(squaredVelocity);
   this.velocity.x *= scalar;
   this.velocity.z *= scalar;
}

The book doesn't explain it. I've been staring at it for an hour. I can see exactly what it does (in the technical sense), but what's its purpose?

I understand bits: The scalar variable is always a fraction, so multiplying the velocity by it scales back that velocity.

Is this code for limiting speed? Then why are the x and y velocities added together? Shouldn't the X and Y be scaled independently?

Do I need to know this stuff for a career in video games? I understand that all this math is educational, but will I still have to do this sort of thing in an engine like Physijs?


texts: What is the difference between Character Modeling and Level Design?

texts:
I'm  thinking of either focusing on character modeling or level design, but I'm not sure what the differences are. Do companies consider them as separate jobs because I don't know that either.

My background: Currently I'm in an associates program for Game Programming, but over the last semester due to my work schedule there was no programming class available for me to take so instead I decided to take 3D Modeling. But as I'm reaching the end of the class I noticed I'm enjoying the 3D Modeling a lot more than programming, so I decided to stick with the art side. However, due to unforeseen circumstances, I'm going to have to move soon and transfer to a new university. Now this new university that I'm going to be attending how the program is set up so that you're required to pick a particular area to focus on. But I'm not sure what to do.


texts: Why is an empty Unity Iphone Build over 700 Megs? Is this Normal?

texts:
So after 2 weeks of slaving over my first game I was finally done! I was entirely ecstatic....until I saw its file size.
770 Megabytes
For a simple numbers game, that was way too much and I created an empty unity project as a test and that was also over 700 megs
Why is an empty Iphone project this large?


texts:
I've made 3 absolute layers

Each layers has it's own animation cycle. Now I would like to export it as FBX and import to unity3d, however, it would import only active layer.
Is it possible to export it the way, it would be possible to choose later on in unity which animation cycle to play?

Thanks in advance


texts: How should I structure a Shared Library for different platforms for my MonoGame project?

texts:
I am quite new to the MonoGame/XNA framework and i have some structuring questions right now.

One of the reasons I use MonoGame is because there is still that feeling to create a game from scratch without such things as Scene Editors. But also the platform independence plays an important role in my project.

I am trying to create a small 2D-RPG that should run on Windows (not Windows Apps) and on android. iOS is optional for now.

Now I thought it would be nice if I can have some kind of Shared Library where the core of the game is inside as a single project. Then I would create a project for Android specific and Windows specific and maybe later iOS specific.

I was thinking of "just" referencing this Shared Library in every platform project and using the games functions in there.

Is this a good idea and even possible? Because in my whole opinion it's redundant code if I create a project for every platform and put whole game code in every project. If I then want to change something, I need to change it for Android, Windows and later iOS too.

The only problem is, Android can only reference PCL libraries right? That's why the shared library must be a PCL then right? Which would be harder for me because I want to use Sockets since the game should get some kind of  small multiplayer.

That's what I am thinking about for now.

I hope you guys know what I mean and if that's not the way I should do it please let me know how you guys would structure your whole project.


texts: When PlayerRemoving event is fired, for loop does not work properly

texts:
while I was implementing the Backback save feature in my Roblox Game (using game.Players.PlayerRemoving:Connect(), I found that when I used a loop of any form (for, while,etc.), it would not run correctly. Here is a test program which I wrote to observe this issue:

game.Players.PlayerRemoving:Connect(function(player)
    local testList = {"Hello", ",", "world"}
    for i=1,3,1
    do
        print(testList[i])
    end
end)

However, when this code is ran, all I see in the output window is:

Hello

And nothing else.
This issue is causing a lot of issues with the rest of the code, can somebody please help? It would be very useful!