texts: updating 2d array to contain chunk of larger 2d array - for 2d tile map

texts:
What i need help with is how can i get a chunk of a large 2d char array and update it so i am only drawing enough tiles to cover the screen?

Currently, i load all the chars from a text file and store them in an array. I then create a smaller array:char[][] toDraw = new char[height][width] which gets the first height*width area of chars from the larger array like this:

  public void filterMap() {
    for(int i = 0; i < height; i++) {
        for(int j = 0; j < width; j++) {
            toDraw[i][j] = MapLoader.mapData[i][j];
        }
    }
}

I then draw the map using this drawMap method:

public void drawMap(Canvas canvas) {
    for(int i = 0; i < height; i++) {
        for(int j = 0; j < width; j++) {
            if(getBitmap(toDraw[i][j]) != null) {
            canvas.drawBitmap(getBitmap(toDraw[i][j]), x + (j*tileSize), y + (i*tileSize), null);
            }
        }
    }
}

note the int x and y are what i increment to move the map, getBitmap(char c) returns a Bitmap from a char, MapLoader.mapData is the 2d array that the text file loads into.

I have tried a few ways of using an offset in the toDraw arrays index to scroll the data relevant to the x,y location but they have been buggy/failed.

So, does anybody have a link to how things like this can be done (I have tried but have found none that help) or could someone with experience in 2d games please tell/show me how this should be done.

Currently my code will get a area from the larger array and draw it to the screen, the only problem is updating the data in the toDraw array. thanks.

The game is made for android but is not included in tags because i dont feel it is relevant to the problem


texts: Using Perlin/Simplex noise in a 2d tile game for terrain generation

texts:
I've been doing a bunch of research regarding procedural 2d terrain generation and have come to the conclusion that the use of perlin/simplex noise seems to be the way to go for most things.

I've copied the code from opensimplex noise and generated some noise, but I'm not really sure what to do with that? How can I take this noise and use it to create terrain similar to games like Diablo2 or Path of Exile? Things placing trees and rivers, etc.

Also, would it be possible to use this to create simple tiles for my game? Say I wanted to create a bunch of different grass tiles(Isometric), would I be able to do this?

EDIT:
So I've tried the following code to try and generate some natural looking rock placements and I'm not quite sure I understand how it's working. I've used the condition value < .1 for placing a rock, but the world seems to be full of rocks. Am I doing something wrong, or am I just not understanding how it's supposed to work?

    private void populateObjects(TileLoader tileLoader)
    {
        OpenSimplexNoise noise = new OpenSimplexNoise();

        for (int i = 0; i < layers[1].layerData.GetLength(0); i++)
        {
            for (int j = 0; j < layers[1].layerData.GetLength(1); j++)
            {
                double value = noise.Evaluate(j, i);
                if(value < .1)
                    layers[1].layerData[i, j] = tileLoader.getTileByName("grassrock");
            }
        }
    }

Here's a screenshot of something this produced:


texts: How to delete only a fragment of sprite in unity (not mesh)?

texts:
I am building a dash effect in unity and I am able to. But when dashing I want to destroy every "particle" in my dashing way. This "particle" I mention is not a whole gameObject but only a fragment of a gameObject that my gameObject can touch. For instance: If my character is 10 cm tall and the gameObject obstacle is 20 cm, I want only the 10 cm to destroy which my character touches.

I have seen a couple of tutorial videos but I am only able to see the tutorial for meshes and 3D objects but not 2D sprites. So, how do I achieve this?


texts: Can global Illumination via path tracing replace all other current lighting techniques?

texts: In the sense that you currently have algorithms like HDR, shadows, reflections, caustics, motion blur and so on, does complete path tracing take care of all these effects, or would you still have to implement these effects separately?


texts: I have a client that sends data at 1KHz (i.e. 0.001 sec) to a master over Internet using UDP protocol. In Master, I need to draw an object, but the problem is that the update of GLUT is slower than the client's update. I have tried to use glutTimerFunc(0,glutIdle, 0); but still slow. Is there a way to speed up the update rate of drawing? I need to update Display() every 0.001 sec. Any suggestions? I'm using windows 7.


texts: My displayed Tiled map is rendered with different tile indexes than in the editor in Slick2D. Why?

texts:
The first picture is what I have in the editor and the second one is what I got when I rendered my map.

@Override
public void init(GameContainer container) throws SlickException {
    this.container = container;
    this.map = new TiledMap("/src/main/resources/map/test2.tmx");
}

@Override
public void render(GameContainer container, Graphics g) throws SlickException {
    this.map.render(0, 0);
}

I would expect the two to be the same, but they're not. Why is that?

Edit : I solved the problem by removing the margin when I imported my tilset


texts: Rotating a parent rectangle to align child with target

texts:
My beautiful drawings will explain better than many words (or at least I hope):

The structure:

The black rectangle is a GameObject (my weapon sprite).
A and B are also GameObjects (children of black rectangle): StartShotPoint and ShotPoint used for the direction of my projectile.
C is the first hypothetical target

In this situation my sprite will be rotate of 0 degree.

In this second image there is the question. I want to find the rotation of my sprite (-10 degree in the example) knowing the Vector2 destination D and of course all the coordinates of the 3 GameObjects.

The situation is simple as long as the player rotates the weapon, but in this case is the AI (after finding the player at the point D) must turn the weapon in the right direction. I know how to find the direction between one point and another, but between two decentralized points and a third one messed up my brain.

I really don't know which "direction" to take.

Thanks for your help.


texts:
I build simple directx 11 application in c++ that draw square to screen.

Also check in the end of the program when I close the last peace of directx the number of free reference.

This work great in normal window but in full screen the reference count return 1.
I did some checks and I realised that if I destroy the window before I am closing the swap chain it works even in full screen.

My question is how can I close the swap chain with reference count of 0 without destroying the window before.


texts: Data-oriented design and Component Sytem cross-referencing

texts:
Let's assume we're talking about a game (engine) which is written in C++. This is more like a design question but I can't find any suitable description.

Component System

The Component System says that an Entity in the world is defined by its components. This system is flexible, modular and really powerful. I've used Unity (a lot) and I like its concept. This also solves the traditional class-hierarchy problem.

Example components:

StaticTransform: Position, Rotation, Scale - a StaticTransform can be a child (and of course a parent) of another StaticTransform (this describes the Entity-hierarchy in the scene)
Rigidbody/Transform: Position, Rotation, Force, etc. - I could use the StaticTransform data, but I'd like to separate the concepts. That's why I have Position and Rotation (but not Scale) data. A Rigidbody can not be a child of another object but can be a parent of StaticTransform.
MeshRenderer: LocalBounds, WorldBounds, Mesh, Material - this component is used to generate draw calls to render the mesh with a specific material.
AudioSource: AudioData - A simple audio source which can be world-space (using one of the transforms) or global (in this case the transform component is irrelevant)
AudioListener: Only one AudioListener is allowed. Most of the time it's added to the player's Entity. It uses the transform's data.
Camera: FoV, Clipping planes, etc. - Of course a Camera can be used to render the meshes from that point of view. Multiple cameras are allowed.

Data-oriented design (DoD)

The key concept of the DoD is to focus on data and data-access instead of code. There are some additional "rules" like: "When there is one, there are many". Most of the time this means that the data itself is stored in a cache-friendly way: contiguous memory with linear access (aka. iterating the array one-by-one). In a "Component System world" the component itself does not exist but the corresponding system stores and manages the data.

In a system like this, raw or managed pointers are forgotten, instead ids and/or handles (special id with additional info) are used. Most of the time a special entityId -> componentId map is used to match the entity to the component. This way the component data can be packed (moved in the array) so the iretation is fast (cache-friendly).

In theory this work really well. Blog posts and other discussions show examples how to do it with a single "component". However I cannot find any good solution to the cross-referencing problem.

The cross-reference problem

Using the example components described above: The MeshRenderer depends on the (both static and dynamic) Transform component because the World matrix is requried to render/cull the mesh. The AudioSource, Camera and AudioListener also depend on the Transform component.

The entities can be arranged into a hierarchy using the Transform's parent-child relation. When the user updates the transform of a root object, every child Transform must be updated as well. This means we are jumping back-and-forth in the memory.

Rendering all meshes all the time seems to be a bad idea. That's why people implement spatial trees which can be used to cull meshes and other renderable objects efficiently. Again, this kills the cache-friendly part.

Question

Should I even use the DoD concept in a complex system like this? The hierarchy, the spatial trees and the cross-referencing kill the linear access (so the cache/prefetcher-friendlyness) advantage. It seems using a "stable vector" (adding/removing elements and resizing the container do not invalidate iterators) is not worse than packed vectors.

Is there any good solution to the problems described above? I like the key concept of the DoD but I'm failing to apply it.


texts:
I'm making a turn based game in java for fun, it follows a set game flow pattern contained in a loop. I realized that once a player hits a win condition the game continues playing out the rest of the turn, possibly changing the victor.

Do I need to go back and put if statements everywhere so nothing is executed once a victor is declared? Is there a more elegant solution?


texts: How to deal with two different axes on isometric game?

texts:
Hi! Above is a visual of the problem I am having. My game has two different coordinate systems. You have the client, or the canvas, where the game is rendered - a standard coordinate plane; however, I also have the game coordinate plane where it is rotated due to the isometric nature of the game.

Note: The server only feeds chunks of tiles to the game at a time, which makes it impossible for me to just translate the canvas. I have to calculate the drag amount and in what direction, and request the new chunk of tiles to be displayed from the server.

My problem: I can't figure out how to calculate the # of tiles moved (so I can send that data to the server), because I don't know how to determine how many tiles and in what direction the user moves the map. Because if they move to the left, it's not only change the game's x position, but also the game's y position because both new columns and rows would have to be loaded due to the nature of the isometric map.

I hope this made sense, I tried my best to explain the problem and I'm not too sure I explained it correctly.


texts: 2d Circle different ARC's Collision detection

texts:
I've read about the way to detect collision between 2 circles or circle and line
using trigonometry.

But now I would like be able to detect which part of the circle arcs I'm hitting.
For example I divided my circle to 4 different sized arcs.
I would like to know which arc gets hit, 1, 2, 3, or 4?
See image:

What is the best collision detection algorithm for this? Or what is this called?


texts:
How do you create an SQL database (I believe it's tinySQL/SQLite) using Adobe Air? I have searched around, and all sites give code, and then explains to wrap it within an xml document, for example here.

So I have created this xml file, but no one seems to explain what to do from there. I am also VERY new to database creations and management. So any super n00b friendly help would be much appreciated.

Thanks.


texts: Will multi-touch become an important/standard method of input for PC games in the future?

texts:
We've seen that multi-touch on smartphones has been wildly successful. On the iPhone, in fact, it's the only tactile input the user can provide! However, I'm wondering how likely it'll be for multi-touch to take off on desktop PCs (and PC gaming) in the future. Right now, it's mostly a lack of good multi-touch monitors on the market, but the fact that there's not much of a push by manufacturers is disconcerting. It'd be really nice to have multi-touch gestures to navigate in an RTS, for instance, and music games would be really fun with multi-touch input (think Elite Beat Agents or DJ Max Technika, but on the PC). An example.

Do you think that multi-touch for PCs will eventually take foot and become popular, or will it stagnate?

P.S. I'm guessing this would be best suited for CW, so if a mod feels like it's appropriate, feel free to mark it as such.


texts:
I'm trying to make a dialogue between characters using bubbles witth text. But the text appears not clear to player.

The Cam is far from the canvas 13.5f. What to do fix it ?


texts: How to setup engine properly in ktx-ashley?

texts:
I'm trying to setup simplest Ashley project with only 2 entities and get this error:

Exception in thread "LWJGL Application" java.lang.IllegalStateException: createComponent(T::class.java).apply(configure) must not be null

Here is the code:

class AshleyScreen(game: Main): KtxScreen {

    private val engine = Engine()

    override fun show() {
        engine.add {
            entity {
                with<DrawableComponent> {
                    sprite = Sprite(Texture("image1.png"))
                }
                with<TransformComponent> {
                    position.set(0f, 400f)
                }
            }
            entity {
                with<DrawableComponent> {
                    sprite = Sprite(Texture("image2.png"))
                }
                with<TransformComponent> {
                    position.set(500f, 50f)
                }
            }
        }
        val renderSystem = RenderSystem()
        engine.addSystem(renderSystem)
    }

    override fun render(delta: Float) {
        engine.update(delta)
    }
}

// Components
class DrawableComponent(var sprite: Sprite): Component
class TransformComponent(val position: Vector2 = Vector2()): Component

//Systems
class RenderSystem: IteratingSystem(allOf(DrawableComponent::class).get()) {
    val batch = SpriteBatch()
    val tm = ComponentMapper.getFor(TransformComponent::class.java)
    val dm = ComponentMapper.getFor(DrawableComponent::class.java)

    override fun processEntity(entity: Entity, deltaTime: Float) {
        val t = tm[entity]
        val d = dm[entity]
        d.sprite.setPosition(t.position.x, t.position.y)

        clearScreen(0.8f, 0.8f, 0.8f)
        batch.begin()
        d.sprite.draw(batch)
        batch.end()
    }
}

Compiler complains on engine.add line.


texts:
I have an issue with objects moving roughly twice as far as expected when dragging them.

I am comparing my application to the standard TouchGestureSample sample from MSDN.

For some reason in my application gesture samples have fractional positions and deltas.

Both are using same Microsoft.Xna.Framework.Input.Touch.dll, v4.0.30319.

I am running both apps using standard Windows Phone Emulator.

I am setting my break point immediately after this line of code in a simple Update method:

GestureSample gesture = TouchPanel.ReadGesture();

Typical values in my app:

Delta = {X:-13.56522 Y:4.166667}
Position = {X:184.6956 Y:417.7083}

Typical values in sample app:

Delta = {X:7 Y:16}
Position = {X:497 Y:244}

Have anyone seen this issue? Does anyone have any suggestions?

Thank you.


texts: Why the Render texture is not working when trying to preview a camera on a object?

texts:
In the editor in Assets right click Create > Render Texture
Then changed the Render Texture name to: SecurityCameraTexture

Dimension 2D size 480 x 256

Then created a new material Assets right click Create > Material
Then changed the material name to: SecurityFootage

Then changed the material shader from Standard to Mobile/Diffuse

Then dragged the render texture(SecurityCameraTexture) to the top right image place of the SecurityFootage(material)

Next I have a tv object in the scene.
In the tv screen I dragged the new material:

The SecurityCamera. On the SecurityCamera I attached the script that rotate the camera from side to side:

And the script:

using UnityEngine;
using System.Collections;

public class scr_camera : MonoBehaviour {

    public float rotate_amount;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        transform.rotation = Quaternion.Euler(transform.eulerAngles.x, (Mathf.Sin(Time.realtimeSinceStartup) * rotate_amount) + transform.eulerAngles.y, transform.eulerAngles.z);
    }
}

Last step I did was to drag the render texture(SecurityCameraTexture) to the camera Target Texture.

When running the game and watching the tv I don't see the camera preview in the tv. It should the show the camera preview the camera moving from side to side and what the camera is showing.

The camera preview was working fine before I started working with the render texture. But it's not showing the preview in the tv.


texts: Skyrim Creation Kit - Call External DLL Method

texts: I've been developing for a few years now but I'm fairly new to creating Skyrim mods. I'm wanting to build a custom DLL and call the methods from scripts in Skyrim. Can I do this and if so, how do I import the DLL and make a call to one of it's methods?


texts: Constraining camera bounds within bounds based on Unity UI object dimensions

texts:
I have a perspective camera which has bounds which I wish to constrain within larger bounds.  All the bounds are calculated in world space.

The code for containing the camera within the constraining bounds is straightforward:

        var camRect = this.cameraComponent.GetCameraWorldRect();
        var correction = Vector3.zero;

        if (camRect.xMin < constrainingRect.xMin)
        {
            correction.x += Mathf.Abs(constrainingRect.xMin - camRect.xMin);
        }

        if (camRect.xMax > constrainingRect.xMax)
        {
            correction.x -= Mathf.Abs(constrainingRect.xMax - camRect.xMax);
        }

        if (camRect.yMin < constrainingRect.yMin)
        {
            correction.y += Mathf.Abs(constrainingRect.yMin - camRect.yMin);
        }

        if (camRect.yMax > constrainingRect.yMax)
        {
            correction.y -= Mathf.Abs(constrainingRect.yMax - camRect.yMax);
        }

        this.cameraComponent.transform.position += correction;

This can be visualized as:

The problem I am facing is that I have a UI object that is covering the right hand side of the screen and I am uncertain how to correctly calculate the width of the UI object so that the constrained camera bounds can take it into account.

The camera that is drawing the UI object is configured as follows:

The camera that is being constrained is configured as follows:

Apart from the layer, the parameters which affect the rendering of the objects for each camera configuration are the same.

The UI object has the following configuration with a Canvas Renderer:

This is how I am currently attempting to calculate to width of the UI object but given that the UI is being rendered using a perspective camera I wasn't too certain that ScreenToWorldPosition was correct.

    private float CalculateMenuWidth()
    {
        // Generate padding to account for the side menu
        var canvas = LevelEditor.Instance.Menu.GetComponentInParent<Canvas>();
        var menuRect = LevelEditor.Instance.Menu.GetComponent<RectTransform>();
        var menuRectMax = menuRect.rect.max * canvas.scaleFactor;
        var menuRectMin = menuRect.rect.min * canvas.scaleFactor;

        if (this.cameraComponent.orthographic)
        {
            return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(menuRectMax).x - this.cameraComponent.ScreenToWorldPoint(menuRectMin).x);
        }

        // Perspective camera requires distance for ScreenToWorldPoint
        var distance = Mathf.Abs(this.cameraComponent.transform.position.z);

        return Mathf.Abs(this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMax.x, 0f, distance)).x - this.cameraComponent.ScreenToWorldPoint(new Vector3(menuRectMin.x, 0f, distance)).x);
    }

However, the size of menu returned by the method above appears to be too large.

How can I correctly calculate the width of the UI object so it appears that the camera constraints do not allow the camera to travel past the UI object?

EDIT: I've added a link to a Unity project which is the minimal working example for reproducing the issue.

https://www.dropbox.com/s/mq36mfqz5wvvsch/CameraConstraintGUIIssue.zip

The camera can be controlled with WASD to translate and the Shift key will speed up the movement.

The camera is constrained inside the checkerboard.  An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu.  Unfortunately, I can't seem to calculate the size of the menu correctly so this occurs.

The code for constraining the camera and calculating the menu size is in EditorCamera.cs.

Edit2:

The constraint from KingDolphin

The constraint I am attempting to calculate (quoted from above, An offset is created so that the camera should stop moving to the right once the right edge of the checkerboard is adjacent to the left edge of the menu.):


texts:
I'm writing a 2D game where the player has to kill a Ninja. This Ninja is coming closer with a constant speed chasing the player.
The Map has some static obstacles like stones no one can pass.
The player can move too and has different types of weapons to damage the Ninja in different ways:

Laser: instantly on whole range
Gun: projectile (circular) following a fixed path
Trap: circular floor ability which detonates after time

I want the Ninja to dodge those Weapons the best he can, he is allowed to take some damage, the least is preferred.

I now have different ideas how to achieve that:

A* with 3rd dimension (time): This is working but the paths are ugly and post processing is not my favorite. Also the Graph's size is about 1000x1000, making it inefficient (on creating neighbors), i try to reduce node count by scaling the nodes to unit.hitbox (40px), which drastically improves the calcs, but the paths look even more ugly..
Theta*: won't work even tho I love it, but line-of-sight on moving obstacles is...
Visibility Graph: same as Theta*, moving obstacles...
Steering: haven't tried this one yet how it performs with constant speed and moving (, delayed) obstacles
Local Avoidance: won't work as the weapon speed is bigger than Ninja movement speed
Geometry: tangents, vector projection etc....  could work well if there aren't much obstacles to dodge

Do you have any other ideas how to achieve some good doing for the poor Ninja?

(NINJAS USUALLY DODGE EVERYTHING... That's why I also plan to give the Ninja a Ninja-Roll feature he can use every 10s to dash on some position if he can't dodge something)

Representation of the raw map (little dots are 40px)

A* Pathfinding with time dimension and a 5px-Grid

Edit: I'll check out D*-Lite and RRT*-Smart

Edit #2: Both are not what im looking for, i will try to optimize A*


texts: MonoGame not all letters being drawn with DrawString

texts:
I'm currently making a dynamic user interface for my game and are setting up having text on my buttons. I'm having an odd issue where, when i use a specific piece of code to determine the text position, it will not render all of the text passed to DrawString. Even weirder, is if i insert another DrawString after this, drawing more text at a different place, different parts of the text will be drawn.

The code for drawing my button with the text attached is:

public override void Draw(SpriteBatch sb, GameTime gt)
{
    sb.Draw(currentImage, GetRelativeRectangle(), Color.White);
    sb.DrawString(font, text,
        new Vector2(this.GetRelativeDrawOffset().X + this.Width / 2 - font.MeasureString(text).X / 2,
            this.GetRelativeDrawOffset().Y + this.Height / 2 - font.MeasureString(text).Y / 2), textColor);
}

The methods in the creation of the Vector2 simply get the draw position of the button. I'm then doing some calculation to center the text.

This produces this when the text is set to 'Test':

And when i enter this piece of code below the first DrawString:

sb.DrawString(font, "test", new Vector2(500, 50), Color.Pink);

I should mention that that grey square is being drawn in the same spritebatch, before the button and the text.

Any ideas as to what could be causing this? I have a feeling it may be due to draw order, but i have no idea how to control that.


texts: Number Guessing Game: How to ensure player cannot be dishonest about their guess

texts:
I'm building a number guessing game in Unity. The computer has 10 chances to guess the number the player is thinking of. The player interacts by pressing Higher or Lower or Correct Guess.

The basic game works fine, as long as the player is honest. I'm now trying to make the game watertight and prevent any user error or dishonesty about their number. I created some test conditions to check if the random number generator has produced a number already used before, or to check if the player is pressing Higher or Lower beyond the max and min guess range.

The problem can be demonstrated well by constantly pressing Lower to the point where the final guess is the number 1. Pressing Lower again results in the game freezing. It also happens if the number you are thinking of is displayed and you press Higher or Lower towards a range of numbers which have already been eliminated as possibilities. I am thinking this is due to the game getting stuck in my while loop in MakeGuess().

I think the problem lies in the following test condition in MakeGuess() but any tweaks I make seem to have no effect:

// check if number has been guessed before
if (newGuess == guess && (newGuess > max || newGuess < min)) {

I've uploaded my current playable build to GameBucket.io here: https://gamebucket.io/game/07cc2b61-493b-46ae-a446-aeaa98ffac0e

All the game logic is handled in the NumberWizard script which is attached to the NumberWizard GameObject in the main Game scene:

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class NumberWizard : MonoBehaviour
{
    int max;
    int min;
    int newGuess;
    public int guess;
    public int maxGuessesAllowed = 10;

    public Text text;
    public Text guessesRemaining;

    // Use this for initialization
    void Start()
    {
        StartGame();
    }

    void StartGame()
    {
        max = 1000;
        min = 1;

        MakeGuess();
        UpdateDisplay();
    }

    public void GuessHigher()
    {
        min = guess;
        NextGuess();
    }

    public void GuessLower()
    {
        max = guess;
        NextGuess();
    }

    public void GuessCorrect()
    {
        StartGame();
        SceneManager.LoadScene("Lose");
    }

    void NextGuess()
    {
        if (maxGuessesAllowed <= 0) SceneManager.LoadScene("Win");

        MakeGuess();
        maxGuessesAllowed -= 1;
        UpdateDisplay();
    }

    void UpdateDisplay()
    {
        text.text = guess.ToString() + " ?";
        guessesRemaining.text = maxGuessesAllowed.ToString();
    }

    void MakeGuess()
    {
        //guess = (max + min) / 2; // old guessing method

        bool validGuess = false;

        while (validGuess == false)
        {
            newGuess = GenerateNumber();

            // check if number has been guessed before
            if (newGuess == guess && (newGuess > max || newGuess < min))
            {
                Debug.Log("Number has been guessed before and is already at either range limit.");
                SceneManager.LoadScene("Lose2");
            }
            else if(newGuess == guess)
            {
                newGuess = GenerateNumber();
                Debug.Log("Number has been guessed before but is not at range limit.");
            }
            else
            {
                validGuess = true;
                guess = newGuess;
                Debug.Log("Number has not been guessed before.");
            }

            Debug.Log("Min: " + min);
            Debug.Log("Max: " + max);
            Debug.Log("====================");
        }
    }

    int GenerateNumber() {
        int result = Random.Range(min, max + 1); return result;
    }
}

Any help with the code


texts: Letting the user draw a Polygon Body and Image

texts:
In my game, I want to provide the user with a drawing feature.

By free hand drawing, the user creates a polygon shape. Then, in my game implementation, I have to create a body for the found vertices and generate an image based on that polygon shape.

My problem is how to create an image that matches the user-provided vertices. I've heard that cocos2d has something called Image Masking. I don't understand how I could implement it in AndEngine. Could someone help?


texts: Center directional light shadow to the cameras eye

texts:
I'm currently drawing my directional light shadow using this view and projection:

XMFLOAT3 dir((float)pitch, (float)yaw, (float)roll);
XMFLOAT3 center(0.0f, 0.0f, 0.0f);

XMVECTOR lightDir = XMLoadFloat3(&dir);
XMVECTOR lightPos = radius * lightDir;
XMVECTOR targetPos = XMLoadFloat3(&center);
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

XMMATRIX V = XMMatrixLookAtLH(lightPos, targetPos, up); // This is the view

// Transform bounding sphere to light space.
XMFLOAT3 sphereCenterLS;
XMStoreFloat3(&sphereCenterLS, XMVector3TransformCoord(targetPos, V));

// Ortho frustum in light space encloses scene.
float l = sphereCenterLS.x - radius;
float b = sphereCenterLS.y - radius;
float n = sphereCenterLS.z - radius;
float r = sphereCenterLS.x + radius;
float t = sphereCenterLS.y + radius;
float f = sphereCenterLS.z + radius;
XMMATRIX P = XMMatrixOrthographicOffCenterLH(l, r, b, t, n, f); // This is the projection

Which works prefect if the center of my scene is at 0.0, 0.0, 0.0. What I would like to do is move the center of the scene relative to the cameras position. How can I do that?


texts: How to store and use different AI behaviours

texts:
I'm coding a space shooter on three.js (WebGL) and since the game I'm doing is rather simple, plus I want to keep controll of the structure, I'm not using a game engine.

I'm using oop classes and inheritance to optimize code reusability and maintenability.

The classes so far look like the following :

MovingObject, the base class possessing the attributes : position, speed, weapon, mesh, etc.

Asteroid, inheriting MovingObject

PlayerShip, inheriting MovingObject

Weapons, Base class of other weapons, possessiong the class shoot, that every other inheriting class redefines in order to shoot the projectile it wants at the position and frquency it wants

MovingSystem, Base class of other moving classes, possessing the function update(inputs,time) that move the MovingObject according to the class behaviour

What I'm searchign is a common architecture / data-model of how an AI controlling an enemy space ship should look like.

So far I've only found algorithms of A* search, a following / escaping path search, etc.

However I don't need the logic code, I want the structure of HOW and WHERE to execute the AI. (If possible in an oop model, so there can be inheritances with slight variations)

I'll post an example of code here, so you see how the code actually use the different classes and inhertance :

//MovingObject class
MovingObject.prototype.update = function(time, inputs)
{
    this.lastPos = this.mesh.position.clone();
    //console.log("this: ",this);
    //console.log("inputs: ", inputs);
    this.movingSys.move(this, time, inputs);

    this.particularUpdateFunctions(time);
};
//PlayerShip class
function PlayerShip(MAX_SPEED, speed, COEFF_ACCEL, mesh)
{
    this.particularUpdateFunctions = function(time){
        this.weapons[this.currentWeap].update(this,time, this.shooting);
    };
}


texts:
i'm making map for a game and need to make scrolling of map, so the main thing what i need is to calculate speed and move layer after player remove finger from screen.

I make it my own, but i think that it must be better decisions:

- (void)touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    _isDragging = YES;
}
// ON TOUCH MOVING
- (void)touchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
CGPoint previous = [[CCDirector sharedDirector] convertToGL:previousLocationOne];
        CGPoint current = [[CCDirector sharedDirector] convertToGL:touchLocationOne];

        CGPoint delta = ccpSub(current, previous);
        _gameLayer.position = ccpAdd(_gameLayer.position, delta);
}

- (void)update:(CCTime)delta {

    CGPoint position = _gameLayer.position;
    static float friction = 0.86f; //0.96f;

// AFTER MOVING ENDED
    if(!_isDragging) {
        _velocity = ccp(_velocity.x * friction, _velocity.y *friction);
        position = ccpAdd(position, _velocity);
        _gameLayer.position = position;
    } else {
        _velocity = ccp((position.x - _lastPos.x)/2, (position.y - _lastPos.y)/2);
        _lastPos = position;
    }
}

This method is working, but i think that in update method if !_isDragging i need to calculate speed of layer with delta isn't it ? So the question is:
If my method is good for "after touch scrolling effect, or i need to use delta ?
Sorry for english.


texts: Game uses gamecenter in iphone - can I design a fallback for 3G and prior devices?

texts: If I develop a game using gamecenter, does itunes connect lock me in to only supporting 3GS and above with iOS 4.0 and above, or will it still allow sales of my game on older devices (as long as I build in fallback so it never calls gamecenter framework)?


texts: How to jump exactly X meters in Box2D World?

texts:
I want my character to always jump a constant height, let's say 3 meters. Also character has double jump ability so he can jump max 6 meters. For example, let's say I have pressed jump key while player is on the ground, and as soon he reaches 1 meter in height, I press jump key again and he performs double jump and reaches 4 meters.

I am really new to box2d and I have figured out that I can make my character jump using body.applyForceToCenter(new Vector2(0, 700), true) but I do not know how much force I need to apply in order to make my character jump exactly 3 meters and perform double jump to jump again exactly 3 meters.

I think what I really need here are just formulas...


texts: Someone downloaded my game but it failed on Game Start due to code that doesnt exist

texts:
As stated in the title, they get the following error:

 ############################################################################################
 FATAL ERROR in
 action number 1
 of Other Event: Game Start
 for object obj_music_controller:

 ds_map_find_value argument 1 incorrect type (undefined) expecting a Number (YYGI32)
 at gml_Script_scr_checkLastLoggedInJson
 ############################################################################################
 --------------------------------------------------------------------------------------------
 stack frame is
 gml_Script_scr_checkLastLoggedInJson (line -1)
 gml_Object_obj_music_controller_Other_2

The function ds_map_find_value() is not being called in the script scr_checkLastLoggedInJson(). (Even if it was, how could it be happening at line -1?)

Nor is it called in the Game Start event of the obj_music_controller object.
I also checked every use of ds_map_find_value() in the entire game and they are all fine.

Furthermore, this is only happening with 1 person. And they have tried uninstalling it and re-downloading. Even after i uploaded a new version of the game, this still happened to them and only them.

EDIT: scr_checkLastLoggedInJson()

var result = false;

if (file_exists("saveJson.json"))
{
    var saveJson = scr_loadJSONFromFile("saveJson.json");//ds_map
    var saveJsonNames = saveJson[? "Names"]; //ds_list
    var userSaveData = noone;
    var saveJsonSaves = noone;

    if (ds_list_size(saveJsonNames) == 1) //If there is only 1 user, that is the one to load.
    {
        result = true;
        var username = saveJsonNames[| 0];
        global.username = username;
    }
    else
    {
        //Find the user who was last logged in and assign them to global.username.
        for (var i = 0; i < ds_list_size(saveJsonNames); i++)
        {
            var username = saveJsonNames[| i];
            saveJsonSaves = saveJson[? "Saves"];//ds_map

            if (!is_undefined(username))
            {
                userSaveData = saveJsonSaves[? username]; //ds_map

                if (userSaveData[? "Last Logged In"])
                {
                    result = true;
                    global.username = username;
                    ds_map_destroy(userSaveData);
                    ds_map_destroy(saveJsonSaves);
                    break;
                }
            }
        }
    }

    if  (ds_exists(userSaveData, ds_type_map))
    {
        ds_map_destroy(userSaveData);
    }

    if  (ds_exists(saveJsonSaves, ds_type_map))
    {
        ds_map_destroy(saveJsonSaves);
    }

    ds_list_destroy(saveJsonNames);
    ds_map_destroy(saveJson);
}

return result;


texts: How to apply object transformations in Godot UI?

texts: E.g I have changed the scale and rotation of a MeshInstance and I want the editor and GDscripts to accept new settings as scale 1 and rotation 0 degrees in all axes.


texts: Difference between "staggered" isometric and "normal" isometric tilemaps?

texts:
The Tiled Map Editor v0.9 recently added support for staggered tilemaps in addition to its usual isometric tilemap support.

What are the exact technical differences between these two types of isometric tilemaps? What are their advantages/disadvantages?


texts: Is multiple material on same mesh cause low perf?

texts:
I'm making something like "Low poly" style game. For that, I'm using multiple materials for each mesh without uv mapping and texturing.

Luckily, only weapon does this, others not. Also it's first person shooter so most of time, it just 7~8 materials requires for rendering.

However, I heard that lots of materials causes more rendering for GPU and it cause performance issue. My target platform is Android, and that could be a big problem.

Should I change all my weapons to have single material each?

This is the screenshot of my game. As you can see, single weapon uses 6 materials.


texts:
I saw a lot of picking code opengl-es, but nothing worked. Can someone give me what am I missing?

My code is (from tutorials/forums)

Vec3 far  = Camera.getPosition();
Vec3 near = Shared.opengl().getPickingRay(ev.getX(), ev.getY(), 0);

Vec3 direction = far.sub(near);
direction.normalize();

Log.e("direction", direction.x+" "+direction.y+" "+direction.z);

Ray mouseRay = new Ray(near, direction);

for (int n=0; n<ObjectFactory.objects.size(); n++) {
    if (ObjectFactory.objects.get(n)!=null) {
        IObject obj = ObjectFactory.objects.get(n);

         float discriminant, b;
         float radius=0.1f;

         b = -mouseRay.getOrigin().dot(mouseRay.getDirection());
         discriminant = b * b - mouseRay.getOrigin().dot(mouseRay.getOrigin()) + radius*radius;

         discriminant = FloatMath.sqrt(discriminant);

         double x1 = b - discriminant;
         double x2 = b + discriminant;

         Log.e("asd", obj.getName() + " "+discriminant+"   "+x1+" "+x2);
    }
}

my camera vectors:

//cam
Vec3 position   =new Vec3(-obj.getPosX()+x, obj.getPosZ()-0.3f, obj.getPosY()+z);
Vec3 direction  =new Vec3(-obj.getPosX(),   obj.getPosZ(), obj.getPosY());
Vec3 up         =new Vec3(0.0f, -1.0f, 0.0f);
Camera.set(position, direction, up);

and my picking code:

public Vec3 getPickingRay(float mouseX, float mouseY, float mouseZ) {

    int[] viewport      = getViewport();
    float[] modelview   = getModelView();
    float[] projection  = getProjection();

    float winX, winY;
    float[] position    = new float[4];

    winX = (float)mouseX;
    winY = (float)Shared.screen.width - (float)mouseY;

    GLU.gluUnProject(winX, winY, mouseZ, modelview, 0, projection, 0, viewport, 0, position, 0);

    return new Vec3(position[0], position[1], position[2]);
}

My camera moving all the time in 3d space. and my actors/modells moving too. my camera is following one actor/modell and the user can move the camera on a circle on this model.

How can I change the above code to working?


texts: I have cars in my unity scene, I am not sure in what units speed is specified in unity.


texts: Understanding the z-axis vector from OpenGL modelview matrix

texts:
I would like to shoot spheres in the current view direction in a simple scene. I use an FPS camera, so no z-rotation. The vector pointing in the correct direction should be (m[8], m[9], m[10]) where m is the modelview matrix as returned by glGetDoublev(...).

In my understanding that vector is normalized, so when I scale it by some scalar its length will equal that scalar. If I draw an object every frame and translate it by the scaled z-axis vector (plus camera position), the object should be directly in front of me, all the time, right?

However, when I run my program, the object is not in front of me all the time. It is in front of me, as long as no rotation around the y-axis is done. Here is the relevant (I think) source code:

/* camera */
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(g_cam.rx, 1, 0, 0);
glRotatef(g_cam.ry, 0, 1, 0);
glTranslatef(-g_cam.tx, -g_cam.ty, -g_cam.tz);

/* get z-axis vector */
double mm[16];
glGetDoublev(GL_MODELVIEW_MATRIX, mm);

/* should be in front of me, all the time */
glPushMatrix();
glTranslatef(g_cam.tx + 10 * mm[8], g_cam.ty + 10 * mm[9], g_cam.tz - 10 * mm[10]);
glColor3f(0, 0, 1);
glCullFace(GL_FRONT);
glutSolidTeapot(2);
glCullFace(GL_BACK);
glPopMatrix();

Note that this is not about how to place an object in front of me all the time, but rather what is wrong with my understanding, that using the z-axis vector does not work here.

I know that this is a frequent question, because I found lots of material on the internet. However, I seem to be missing something yet. It would be great if you could help me with it :)

If the problem is not as obvious as I think it is, I can prepare a small example demonstrating the issue.


texts:
I keep hearing people talk about "dirty rendering" when it comes to map rendering for HTML5. I've Googled and searched the GameDev about it but there isn't much about it.

What exactly is it?
How to implement it properly?


texts: Convert Mouse Coords into Isometric Tile ID

texts:
Using GameMaker Language, I'm basing off their Adavnced Examples. How can i convert the current mouse position into a tile position?

The mouse coordinates are 0,0 from top-left

This is the function when it draws. I think this is what needs reversing. I'm tragically bad at Maths, so I'm sorry in advance.

/// DrawLevel()
var xx,yy,destx,desty, base_x,base_y,current_row_x,current_row_y,tile,o,sp, m,h,offy, tileset;

TileRowDX = 68;
TileRowDY = 34;
TileColumnDX = -68;
TileColumnDY = 34;

MapX = 0;
MapY = 0;
MapDrawX = 11;
MapDrawY = 11;

/// Draw the complete isometric level
tileset = global.tiles;

// End point in map drawing (map coordinates)
destx = MapX+MapDrawX;
desty = MapY+MapDrawY;

// Start drawing position - center in the middle of the screen - and just above a little
base_x = surface_get_width(application_surface)/2;
base_y = 150;

// X and Y loop to print all cells.
for( xx=destx-1;xx>=MapX;xx--) {
    current_row_x = base_x;
    current_row_y = base_y;
    for( yy=MapY;yy<desty;yy++)
    {
        // First draw the column of tiles in this cell, bottom to top.
        offy=0;
        for(var h=0;h<global.mapMaxLayers;h++){
            m = Map[h];         // get 2D map grid from level array (Z axis)
            tile = m[# xx,yy];  // get tile from 2D grid (x,y axis)
            if( tile>=0 ){
                // if we have a tile, then draw it.
                draw_sprite(tileset,tile,current_row_x,current_row_y-offy);
            }
            offy+=27;
        }

        // Next, get the object in this cell, and draw it on top.
        // If allowing height for the player, you'd need to add on 27 for each block up.
        o = Objects[# xx,yy];
        if( o!=0 ){
            // Get the object sprite to draw (could also do frames etc)
            sp=o.Sprite;

            // get a 0 to 1 value into the isometric cell.
            var dx = (1.0/15.0) * ((o.x&15));
            var dy = (1.0/15.0) * ((o.y&15));

            // Move to top left of Isometrix grid cell
            var ox = current_row_x - TileRowDX;
            var oy = current_row_y - TileRowDY;

            // Now convert into an isometric offset on X and Y
            ox = ox + (dy*TileRowDX);                   //Y axis first
            oy = oy + (dy*TileRowDY);
            ox = ox - (dx*TileColumnDX);                // now X axis
            oy = oy - (dx*TileColumnDY);

            // and draw this sprite
            draw_sprite(sp,0,ox,oy);

        }

        // Move down and right
        current_row_x += TileRowDX;
        current_row_y += TileRowDY;
    }
    // Back up to top, and move left and down.
    base_x += TileColumnDX;
    base_y += TileColumnDY;

}

I'm sure this is just mostly a mathematics question!


texts:
I want to develop an MMO, like World of Warcraft, but some basic research says that it is going to take a lot of time and money. I'd like to know why.

Why is it so expensive to develop an MMO?


texts: How can I speed up slow loading of big levels?

texts:
I created a level loader that loads levels saved in an XML format. This means I am using an XML parser to read the levels. It works, but slightly bigger levels take too long to load. So now I am looking for a way to speed up loading. I don't need the whole file to be loaded at once, as the player can't see the whole map anyway, so partial loading would be fine.

I thought about a tile based loading mechanism where there are multiple parts of the map, and the loader only loads the part/tile where the user is standing. But I am not sure if that is a good idea.


texts: Positioning of the game object after scaling the game background

texts:
i'm creating a game using Corona SDK i have a map and with ball and some other object moving on this map
and i'm using the ultimate config.lua file for scaling background based on device screen resolution
my problem is that i want to arrange some object on this map but for device resolution i have created specific assets for ex android device with aspect ratio lower than 1.72 so in this assets the map is stretched horizontally or it's became wider than other assets
so in this case when i want to arrange an object on top of this map the result is
that my object didn't set in the right place and that because the map is became shorter than is other design for more explaining when i set myobject.y=100 on a device with aspect ration more than 1.72 it set on the right place but when i do the same thing on device with aspect ratio less than 1.72 my object didn't set on the map
i tried to convert my pixels to inches using device DPI but it's still the same

sorry for my poor english
and thanks for help


texts: How can I get the pressure of a touch in Unity?

texts: Does anyone know how to get the getPressure function from the Android API into Unity? Or is there another way I can access the pressure of a touch?


texts: How can I translate a game object towards a position?

texts:
I am instantiating my game objects (spheres) through scripts. I want my spheres to move from one location to another. but I don't know how to do this. Update is called once per frame. Is that what I should use? I am using the free version of Unity; I don't want to use special plugins.

How do I move these game objects from one location to another, over time?


texts: Transparent texture over colored polygon?

texts:
Let's say I have a cube with each face having a different colour. I want them all to look like brick walls, but I don't want to have to recreate the same brick texture for every colour.

Is it possible to create a greyscale semi-transparent brick texture that I can overlay overtop of the polygon colour?

This scene will eventually be used in Unity, but I also have access to 3DS Max and Blender. So, whatever works.


texts: How to resolse collision between moving and static AABB?

texts:
What I have is a map represented as list of Rectangles and player's rectangle. Also I have function to determine depth of the collision:
    Point TestAABBAABB(Rectangle a, Rectangle b) {
        Point mt = new Point();

    double rcx = Math.abs(a.getCenterX() - b.getCenterX());
    double rx = (a.width / 2 + b.width / 2);
    if (rcx > rx) {
        return new Point();
    }
    double rcy = Math.abs(a.getCenterY() - b.getCenterY());
    double ry = (a.height / 2 + b.height / 2);
    if (rcy > ry) {
        return new Point();
    }
    double overlap_x = rx - rcx;
    double overlap_y = ry - rcy;

    mt.x = 0;
    mt.y = 0;
    //this is the line
    if (overlap_x < overlap_y) {
        mt.x = (int) overlap_x;
        if (a.getCenterX() < b.getCenterX()) {
            mt.x = -mt.x;
        }
    } else {
        mt.y = (int) overlap_y;
        if (a.getCenterY() < b.getCenterY()) {
            mt.y = -mt.y;
        }
    }
    return mt;
}

It works fine if a player jumps "inside" the width of the wall, far from edges. //tail representation

But if player tries to jump near an edge, he moves through the wall and to the side as a result of non-zero X penetration depth of collision.

How do I avoid this situation so player slides under platform instead of getting pushed left or right and without having to set vx or vy to zero?


texts:
I'm trying to export a Unity Package and it's taking far too long (it just keeps counting, and doesn't end). I'm not sure why it continues to count in the PackageImporter.Tick but I'm wondering if others have noticed performance issues.
Unity Version: 2020.2.3f1
OS: Windows 10


texts:
Edit:-

How do I implement GLEW (or OpenGL extension libraries) within Unity?

Original Question:-

I've recently been looking into some really nice features of OpenGL 3.2 that I want to take advantage of in the development of a tech demo. One example being Geometry Shaders and Tessellation: now I know that OSX 10.8 already implements OpenGL 3.2 but not all of the functionality has been exposed, that is where GLEW comes in.

GLEW is a C/C++ extension... I have very limited C/C++ knowledge, would anyone be able to run through (in layman's terms) how to get GLEW working along side my C# Unity project.


texts: How to only render fragments with Z from 0 to 1 in OpenGL?

texts:
I have been using OpenGL for a year now, but I just recently found out that OpenGL only clips vertices when the absolute value of the x,y or z coordinate is less than the absolute value of w coordinate. Previously I had assumed that the z coordinate would have to be 0 < z < w to be rendered. Is there any way to clip vertices with z less than 0, without a performance hit?

I am using OpenGL 4.4


texts: Dynamic force behind logical jumping on 3 axis'

texts:
I've been working on physical jumping in a 3D environment, I've got it working with a static force. The problem with this is that the force on each axis should be different due to the rotation from the player.

A few things to keep in mind:

A total rotation of 360 degrees can be made;
Forces should never be greater than 0.2 or lower than -0.2;
There is no framework/engine behind the game, it's all hardcore codings.

I've been trying something like;

velocity.x = x - ( x + ( 10 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );
velocity.y = y - ( y + ( 20 * math.cos ( ( rz + 90 ) * math.pi / 180 ) ) );

where x,y is the spawned location and rz is the rotation from the player. This way, I'll get the location from the player 20 units in front of him. By subtracting the actual starting position from it, I should've gotten a velocity. However, this turned out to be wrong. It's not going towards the direction the user is facing, it's just doing it's own simple thing.

The jumping/throwing into 1 direction is working perfectly fine. The calculations I made so far are totally messed up and not working as expected.

The results which I am expecting to get is something like;

force.x = 0.1;
force.y = 0.2;

this can be negative or positive, this should be dynamic though.


texts: Instantly snap into specific directions?

texts:
In my 2d setup, I want the player to constantly move in a specific direction at a set speed. It's similar to "Snake" in that you can only move in four directions and you can't stop your movement.

Right now, the way I do this is by having a char variable "direction", which can either be u, d, l, r (take a guess what those stand for). Based on those letters, I use GetComponent().MovePosition and increase/decrease the position on the x or y axis.

Is there a better way to do this? I would prefer if I could just enter the degree (0, 90, 180, 270) to make the player move in the right direction. I tried AddForce but I couldn't get it to work.

Side note: it's important for me that I can set the direction without player input, as there are some objects that force the player into a different direction.

Edit: As the tag would suggest, I'm looking for a Unity specific answer, as I'm not sure which function would best suit my needs.


texts: How can one achieve the mechanic of hitting cars or bumping into them like in Burnout games' takedown modes?

texts:
In Burnout games there's this game mode where the player can trash other cars by bumping into them or bumping them into walls. As you can see in this video link This is known as a takedown.
I'm working on a racing game and I would like to work on a similar feature. I added a bouncy material to my cars collider in hopes that this effect would be replicated to some degree but all it did was to slightly push the cars away from the player.
I don't have that much experience in making games so I'd appreciate any help I could get about the subject.


texts: Android Game Development problem with Speed = Distance / Time

texts:
I have been coding speed for an object. I have made it so the object will move from one end of the screen to another at a speed depending on the screen size, at the monemt I have made it so it will take one second to pass the screen. So i have worked out the speed in code but when I go to assign the speed it tells me to force close and i do not understand why. Here is the code:

MainGame Code:

@Override
protected void onDraw(Canvas canvas) {
    setBlockSpeed(getWidth());
}

private int blockSpeed;
 private void setBlockSpeed(int screenWidth){
Log.d(TAG, "screenWidth " + screenWidth);
 blockSpeed = screenWidth / 100; // 100 is the FPS.. i want it to take 1 second to pass the screen
 Math.round(blockSpeed); // to make it a whole number
 block.speed = blockSpeed; // this is line 318!! if i put eg block.speed = 8; it still tells me to force close
 }

Block.java Code:

public int speed;

public void draw(Canvas canvas) {
    canvas.drawBitmap(bitmap, x - (bitmap.getWidth() / 2), y - (bitmap.getHeight() / 2), null);
    if(dontmove == 0){
        this.x -= speed; // if it was eg this.x -= 18; it would not have an error

    }
}

The exception

06-08 13:22:34.315: E/AndroidRuntime(2801): FATAL EXCEPTION: Thread-11
06-08 13:22:34.315: E/AndroidRuntime(2801): java.lang.NullPointerException
06-08 13:22:34.315: E/AndroidRuntime(2801):     at com.charltonsantana.game.MainGame.setBlockSpeed(MainGame.java:318)
06-08 13:22:34.315: E/AndroidRuntime(2801):     at com.charltonsantana.game.MainGame.onDraw(MainGame.java:351)
06-08 13:22:34.315: E/AndroidRuntime(2801):     at com.charltonsantana.game.MainThread.run(MainThread.java:64)


texts: Unity 2d_ Constant Player movement along the x axis

texts:
The movement of my player depends on swipes,

swipe left-> character moves to the left

swipe right-> character moves to the right

right now i am only getting a small movement, meaning that the player moves along the X axis but it stops inmediatelly. This is the code i have to check the swipes direction:

PLayer.cs:

public Vector2 desiredPosition;

void Update()
{
    if (MobileInput.Instance.SwipeIzquierda)
    {
        desiredPosition += Vector2.left;
    }
    if (MobileInput.Instance.SwipeDerecha)
    {
        desiredPosition += Vector2.right;
    }

    transform.position. = Vector2.MoveTowards(transform.position, desiredPosition, moveSpeed * Time.deltaTime);

In the MobileInput script i control the swipes:

private const float DEADZONE = 100.0f;
public static MobileInput Instance { set; get; }
private bool swipeIzquierda, swipeDerecha, swipeAbajo, swipeArriba;
private Vector2 swipePuntoAhora, touchComienzo;

public bool SwipeIzquierda { get { return swipeIzquierda; } }
public bool SwipeDerecha { get { return swipeDerecha; } }
public bool SwipeArriba { get { return swipeArriba; } }
public bool SwipeAbajo { get { return swipeAbajo; } }

private void Awake()
{
    Instance = this;
}

// Use this for initialization
void Start () {

}

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

    Debug.Log(SwipeIzquierda);

    swipeDerecha = swipeIzquierda = false;

    #region Input Pc
    if (Input.GetMouseButtonDown(0))
    {
        touchComienzo = Input.mousePosition;
    }
    else if(Input.GetMouseButtonDown(0))
    {
        touchComienzo = swipePuntoAhora = Vector2.zero;
    }
    #endregion

    #region Mobile Input
    if (Input.touches.Length != 0)
    {
        Debug.Log("hola");
        if (Input.touches[0].phase == TouchPhase.Began)
        {
            touchComienzo = Input.mousePosition;
        }

        else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
        {
            touchComienzo = swipePuntoAhora = Vector2.zero;
        }
    }
    #endregion

    #region Calcular distancia

    swipePuntoAhora = Vector2.zero;
    if (touchComienzo != Vector2.zero)
    {
        //Mobile
        if (Input.touches.Length != 0)
        {
            swipePuntoAhora = Input.touches[0].position - touchComienzo;
        }
        //PC
        else if (Input.GetMouseButton(0))
        {
            swipePuntoAhora = (Vector2)Input.mousePosition - touchComienzo;
        }
    }

    #endregion

    #region Calcular DEadzone del swipe

    if (swipePuntoAhora.magnitude > DEADZONE)
    {
        float x = swipePuntoAhora.x;
        float y = swipePuntoAhora.y;

        if (Mathf.Abs(x) > Mathf.Abs(y))
        {
            //Izquierda o Derecha
            if (x < 0)
            {
                swipeIzquierda = true;
            }
            else
            {
                swipeDerecha = true;
            }
        }
        else
        {
            //Arriba o Abajo
            if (y < 0)
            {
                swipeAbajo = true;
            }
            else
            {
                swipeArriba = true;
            }

        }

        touchComienzo = swipePuntoAhora = Vector2.zero;
    }

    #endregion
}

The goal of all of this is to:

If i swipe to te right, the player starts to walk to the right AND continues doing so unless i swipe to the left, only then the player starts to move to the left. I want the movement to be constant in one direction until the other swipe changes it

Any help with this will be really appreciated


texts:
I'm trying to implement a dialogue system for a game in Unity(c#). I'm going to use xml cause I want the dialogues to be editable/added from outside. I have a practical problem.

Let's say I got this line in XML:

<Action character="MC" name="giveItem" item="Potion" quantity="2"/>

This should tell to the inventory system of the main character that it has to give him 2 potions.

As example, not actual implementation:

MainCharacter.Inventory.giveItem("Potion",2)

The question is: With the name and parameters of the method from the XML, how do I call it? And how I call other methods that i'll need in my dialogue scripts? So far I've seen reflection and maybe a dictionary of delegates, but I'dont know is there is a better way and if those are bad practices.


texts: I'm not here to ask about the merits of HTML 5, CSS 3, Javascript, etc. as game development tools.  Lord knows how many people have asked about that already.  No, what I'm curious about is what kind of browsers different types of gamers tend to have.  I'm starting a game development studio, and I want to use some HTML 5 and CSS 3 features on my website.  I know where to look for browser compatibility, but I'd like to know how old a browser I should cater to.  My target audience is primarily teenagers through young adults.  Is there any risk of alienating potential players with fancy HTML 5 features, or is it safe to assume their browsers are reasonably up to date?


texts: Using Lua for configuration and localization data

texts:
Since my game is already going to be scripted with Lua, I've decided to make all my configuration and localization data defined using Lua tables.  For example, this could be a basic locale file:

-- en-us.lua
text = {
    error = {
        sdl = "Error initializing SDL",
        opengl = "Error initializing OpenGL",
        resource = "Error loading resource $",
        -- ...
    },
    menu = {
        offline = "Play solo",
        online = "Play co-op",
        quit = "Quit",
        -- ...
    },
    -- ...
}

Different locales and profiles can be loaded simply by choosing the right file, for example between en-us.lua and fr.lua.

Because the table is in global scope, it's easy for other Lua code to reference.  If a script needed to access a configuration variable or throw an error, it would just have to look up the value using something like text.error.opengl or config.graphics.fullscreen.

The difficulties come when native code (C) has to work with these values.  There are basically two options that I can think of:

The tables are loaded into client code as a tree.  It's easy to get and set values on the client side, but changes on either side need to be synchronized.
The native code does no caching and instead directly reads from/writes to the Lua state each time.  Possible performance issues?

What's the best way to handle this from the native side?


texts: How do I detect when the Xbox home button is pressed XNA?

texts: How do I detect when the big Xbox button in the middle of the gamepad is pressed in XNA?


texts: libGDX How to make camera follow the player?

texts:
I'm having some trouble getting the camera to even work at times. Thankfully, its some-what working now. I'm trying to get the camera to follow the players movement but nothing happens.

(cut out the parts that are useless)

public class GameCore extends Game  {
private OrthographicCamera cam;
private Player player;
private ShapeRenderer shape;

@Override
public void create() {
    cam = new OrthographicCamera(1280 ,720);
    cam.translate(Gdx.graphics.getWidth()/2, Gdx.graphics.getWidth()/2, 0);
    cam.update();

    shape = new ShapeRenderer();
    player = new Player();
    player.setPos((int)cam.position.x, (int)cam.position.y);

}

@Override
public void dispose() {

}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    super.render();
    player.render(shape, cam);
    player.update();

}

GameCore class (my main one)

public class Player {
    public int x,y;
    public int dx, dy;
    public int width, height;
    public double area;
    public int hp;

    public Player(){
        hp = 100;
        width = 1150;
        height = 500;
        area = width*height;
        x = Gdx.graphics.getWidth()/2;
        y = Gdx.graphics.getHeight()/2;
        dx = 5;
        dy = 5;

    }
    public void render(ShapeRenderer shape, OrthographicCamera camera){
        shape.setProjectionMatrix(camera.combined);
        shape.begin(ShapeType.Line);
        shape.circle(x, y, 32);
        shape.end();

    }
    public void update(){
        if(Gdx.input.isKeyPressed(Input.Keys.A)){
            x -= dx;
    }
        if(Gdx.input.isKeyPressed(Input.Keys.D)){
            x += dx;
    }
        if(Gdx.input.isKeyPressed(Input.Keys.S)){
            y -= dy;
    }
        if(Gdx.input.isKeyPressed(Input.Keys.W)){
            y += dy;
    }
}
    public void setPos(int x, int y){
        x = this.x;
        y = this.y;
    }

    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
}

Player class

Hopefully someone here can also point out if i'm doing something wrong with the camera -_-. The docs don't really provide much information on how these classes are used. Thank you! :D


texts: Unity - separate shapes on a map into individual objects?

texts:
Okay, I asked this question yesterday anonymously thus I couldn't edit it so I'm remaking it.

Short version:
I have a transparent map with black borders (Colored map) and I want those shapes formed by these borders to become individual objects in Unity. Is it even possible and if it is, how?

Long version:
I want to make a Grand Strategy type game with provinces and countries. However, I'm not really an experienced graphics nor Unity programmer.

I already have a map drawn with the desired black borders with each province being defined by these very borders and each has an unique color (sort of an identifier). Having just this seems plain and complicated to use so I'd like for each province to emit a color corresponding with a selected map type (diplomacy, terrain, domains, etc.). Obviously, this would be hard to do with just a single plain texture therefore I need to make objects and this is where my inexperience blocks me from continuing.

Is there anything I can do (in Unity and/or Photoshop) that could make the provinces be objects without manually isolating, importing and matching (as a puzzle) each single one?

I've already looked at countless questions and answers but still none fit my problem. I'm at my wits' end with this to the point where I'm actually thinking about scrapping the project.


texts: How do I make my rigid body rotate a fixed angle value each time I click the movement keys

texts:
Ive tried some experiments with the character rotation, but I dont want it to rotate when he touches something, but I also need to unfreeze the Z axis rotation or else the character doesnt rotate when I press a key. My code is this right now, each time I press play (with the Z axis unfreeze) the character just turns like 10 degrees each time I press a key and he is still interacting with objetcs, I dunno what I can do and I might need some help :/

public float speed = 2f;
private Rigidbody rb;
private float midJump = 1;
private Rigidbody rB;

//Character Movement

void Start()
{
    rb = GetComponent<Rigidbody>();
}
void Update()
{
    rb = GetComponent<Rigidbody>();

    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");

    Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical);

    rb.AddForce(movement * speed);

//Character Jump

    if (midJump == 1 && Input.GetKeyDown(KeyCode.Space))
    {
        rb.velocity = new Vector3(0, 45, 0);
        midJump = 2;
    }

//Character Rotation

    else if (rb.velocity.y == 0.0)
        midJump = 1;

    {
        if (Input.GetKeyDown(KeyCode.D))
            rb.AddRelativeTorque(new Vector3(0, 0, 90));
        rb.angularVelocity = Vector3.zero;

        if (Input.GetKeyDown(KeyCode.A))
            rb.AddRelativeTorque(new Vector3(0, 0, -90));
        rb.angularVelocity = Vector3.zero;

        if (Input.GetKeyDown(KeyCode.S))
            rb.AddRelativeTorque(new Vector3(0, 0, 180));
        rb.angularVelocity = Vector3.zero;

        if (Input.GetKeyDown(KeyCode.W))
            rb.AddRelativeTorque(new Vector3(0, 0, 0));
        rb.angularVelocity = Vector3.zero;
    }

}


texts: How to design Client-server hybrid hit detection with projectile weapons?

texts:
Hybrid hit detection here refers to a architecture where client sends a hit claim to server and server verifies it with a tolerable error limit to confirm the hit or deny it.

This technique may work well with hit scan or instant hit weapons because you only have to check it for one frame/tick.
But in case its a physics projectile I.e where an actual projectile flies to the target like a real bullet,  the hit is the result of flight over more than one frames and varying physics state. As such verifying the hit could be very cumbersome and resource intensive.

So how would  one go for server client hybrid approach in this scenario?


texts: gamemaker getting a ball to bounce 90 degrees off of a 45 angle

texts:
I am trying to get a circle to bounce off a 45 degree diamond shap using Gamemaker Studio.
I would like the ball to bounce in straight lines so my directions would be 0, 90, 180, or 270 degrees, depending on which side of the diamond the collision takes place.  Precise bouncing is giving me all sorts of results so I think I would have to do it in code.

I tried saying:

  if (direction >=0 && direction <=90) {   direction = 90 }

And doing this for all the angles, but this did not work.

Has anyone encountered this before?


texts: How to prevent players from forcing the veto-holder to give up their veto power?

texts:
In this game there is a President and the members of the Senate.  Most are good, but a few are evil pretending to be good.  Each day the majority attempts to figure out who is evil (using clues), takes that player to court (where they may argue in their own defense), and then the entire Senate votes on whether to convict that player (eliminate them from the game) or acquit them.

Only 2 such trials are allowed per day (at night, the evil players murder someone), but only 1 conviction per day.

The President may secretly be good or evil, and differs from the rest only in that he has a veto ability.  If someone is taken to court, the President may at any time before the verdict is declared, instantly acquit or convict them.

He may do this only 1 time.

IMPORTANT EDIT: The President must exercise his veto power while voting is in progress, before the decision of the majority has been made public.

The problem is, the other members of the Senate, unwilling to risk the possibility of an evil President overriding the majority decision to convict an evil player at a crucial point later in the game, have developed a meta where the very first time everyone agrees to convict or acquit someone during the first trial of the game, they vocally demand the President to "waste" his veto power in agreement with the majority vote.

If the President refuses they simply take him to court and convict him, eliminating him from the game.

This effectively reduces the President to a normal player.

How can this sort of meta be prevented?

I've tried giving evil players the ability to temporarily disable the President's veto power, in order to give the President a plausible excuse for not using it immediately.  This was an unsatisfactory solution because the evil players did not use it enough for the President's excuse "I was disabled by an evil player" to be convincing.  Evil players simply did not care whether the President could veto because it's too early for them to tell whether the President is on their side or not.


texts: How to compute matrix transform local/world on OpenGL

texts:
I'm developing an OpenGL program where each object / entity contains m_WorldPosition, m_WorldOrientation, m_WorldScale and m_WorldTransform (Vector3, Quaternion, Vector3 and Matrix4f).

The problem is that these transformations are global. So I move, rotate and scale an object / entity I need to use a function that I did.

// C++
void HEntity::translate(const HVec3f& pos, const bool local)
{
    if(local) {
        m_WorldPosition += m_WorldOrientation.toMatrix3() * pos;
    } else {
        m_WorldPosition += pos;
    }

    m_NeedTransformUpdate = true;
}

I wanted to do the same as other software such as Blender or Unity3D 3D where each object / entity contains the variables position, localPosition, rotation, localRotation...

I want a similar system. Where I have the variables position, localPosition, orientation, localOrientation, scale, localScale. But I do not know how to apply it to matrix Each object / entity.

Below is the function to compute the matrix.

// C++
void HEntity::updateTransform()
{
    m_WorldTransform.identity();
    m_WorldTransform.setRotationAxis(m_WorldOrientation.getAngle(), m_WorldOrientation.getAxis());
    m_WorldTransform.scale(m_WorldScaling);
    m_WorldTransform.translate(m_WorldPosition);

    if(m_pParent) {
        m_WorldTransform =  m_pParent->m_WorldTransform * m_WorldTransform;
    }
}

And the game loop

// C++ - Game loop

HGameObject* object = NULL;
int index = 0;

for(; m_ObjectCount; index++)
{
    object = m_pObjectList[index];

    glMultMatrixf(object->m_WorldTransform.getTranspose());

    // Draw current object

    glPopMatrix();
}


texts: Issues making a gradient square in glsl es 2.0, Gamemaker Studio 2.0

texts:
I made a triangle list with 4 triangles, having the middle point a different color. And then aim to combine the triangles to get a nice gradient.
But the edges of the triangles create unwanted lines, I don't want these lines I want it to be smooth al the way.
How can I get the desired result?

Images:

Shader Code:

    // Simple passthrough vertex shader
    //
    attribute vec3 in_Position;                  // (x,y,z)
    attribute vec4 in_Colour;                    // (r,g,b,a)
    attribute vec2 in_TextureCoord;              // (u,v)

    varying vec2 v_texcoord;
    varying vec4 v_colour;

    void main()
    {
        vec4 object_space_pos = vec4( in_Position.x, in_Position.y,         in_Position.z, 1.0);
        gl_Position = gm_Matrices[MATRIX_WORLD_VIEW_PROJECTION] * object_space_pos;

        v_colour = in_Colour;
        v_texcoord = in_TextureCoord;
    }

    //
    // Simple passthrough fragment shader
    //
    varying vec2 v_texcoord;
    varying vec4 v_colour;

    void main()
    {
        gl_FragColor = v_colour;
    }

Gamemaker code:
Create event:

    //Build vertices list

    vertex_format_begin();
    vertex_format_add_position();
    vertex_format_add_colour();
    vertex_format_add_textcoord();
    v_format = vertex_format_end();
    v_buff = vertex_create_buffer();
    vertex_begin(v_buff, v_format);

    //triangle 0
    vertex_position(v_buff, 200, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 0.0);

    vertex_position(v_buff, 600, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 0.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    //triangle 1
    vertex_position(v_buff, 200, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 0.0);

    vertex_position(v_buff, 200, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 1.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    //triangle 2
    vertex_position(v_buff, 600, 100);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 0.0);

    vertex_position(v_buff, 600, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 1.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    //triangle 3
    vertex_position(v_buff, 200, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 0.0, 1.0);

    vertex_position(v_buff, 600, 500);
    vertex_colour(v_buff, c_black, 1);
    vertex_texcoord(v_buff, 1.0, 1.0);

    vertex_position(v_buff,  400, 300);
    vertex_colour(v_buff, c_red, 1);
    vertex_texcoord(v_buff, 0.5, 0.5);

    vertex_end(v_buff);
    tex = sprite_get_texture(sprite_index, 0);

Draw event:

    shader_set(shd_prim);
    shader_set_uniform_f(uni_radius, var_radius);
    vertex_submit(v_buff, pr_trianglelist, tex);
    shader_reset();


texts: How does the rectangle bounds (x,y,width,height) in libgdx work?

texts:
I cant work out how to use the rectangle bounds in libgdx I am currently using the superJumper example and have 2 or 3 examples with that are:

<!--this is the pause button in the top right corner-->
pause Bounds = new Rectangle(320 - 64, 480 - 64, 64, 64);

<!--this is a rectangle resume button in the middle of the
page in the menu that comes up when the pause button is pressed.-->
resume Bounds = new Rectangle(160 - 96, 240, 192, 36);

Basically my question is aimed at the 360 -64 and 160 -96 because I don't know why this is used. I need to create a rectangle that covers the left side of the screen and the same on the right. I want to create some on screen buttons, I have already created the actions for these buttons and I have managed to get them to work but I can't move the rectangles to where I want.


texts: Interpolating from Current- to Target-value every frame

texts:
I have a CurrentValue and a TargetValue.
Every frame, i want the CurrentValue to "lerp" towards the TargetValue.

I always seem to get jitter, because the currentvalue never perfectly hits the targetvalue.
Lets say i have a targetvalue of 5 and a currentvalue of 4, and the speed is 2.
Then the value will go from 4 -> 6 -> 4 -> 6

I have been looking at the Lerp function, but i just don't see how exactly i can use it.

The practical applications im thinking of is accelleration of a car, turning a turret on a tank etc.
What are some best practices on doing the above?

Thanks in advance :)


texts:
I'm toying with creating a tile-based 2D java game engine. I can render the "local" area without issues(I.E. deciding which local tiles to render). The problem came when I introduced floating point locations. I want my "camera" location to be a double. My thought was "I'll multiply the double by the tilesize, round it, and get a pixel approximation". That doesn't work, for one reason or another. The code below is the most functional code I've been able to construct. It works almost entirely correctly except around the 0,0 area it skips tiles(?) and it looks hackish and the code's overall hideous. Is there some easier method I'm missing here, is there an example I can examine?

private HashMap<Integer, HashMap<Integer, Tile>> tiles = new HashMap<>(); // Tiles stored here
public double cameraX = 0, cameraY = 0; // Camera location(centered on screen)
private final int TILE_SIZE = 100; // Size of tiles
private final int TILE_BUFFER = 5; // Buffer of tiles to be rendered/loaded around screen
private int screenTileWidth = 0, screenTileHeight = 0; // Tiles that fit onto the screen

@Override
public void render(Graphics g) {
    // Calculate tile width/height of screen
    int screenWidth = this.screenTileWidth + (TILE_BUFFER * 2), screenHeight = this.screenTileHeight
            + (TILE_BUFFER * 2);

            // Supposedly the offsets from the camera's location to be applied to the rest of the tile locations
    int locOffsetX = (int) Math.round((cameraX % 1) * TILE_SIZE);
    int locOffsetY = (int) Math.round((cameraY % 1) * TILE_SIZE);

            // Big mess of "eww" hackish stuff to fix negatives messing with things
    if (cameraX >= 0 && locOffsetX >= 0) {
        locOffsetX *= -1;
    }
    if (cameraX < 0 && locOffsetX < 0) {
        locOffsetX *= -1;
    }
    if (cameraY >= 0 && locOffsetY >= 0) {
        locOffsetY *= -1;
    }
    if (cameraY < 0 && locOffsetY < 0) {
        locOffsetY *= -1;
    }

            // Base offsets to center tile
    int offsetX = ((GameEngine.g.getWidth() / 2) - (screenTileWidth / 2)
            * TILE_SIZE)
            + locOffsetX;
    int offsetY = ((GameEngine.g.getHeight() / 2) - (screenTileHeight / 2)
            * TILE_SIZE)
            + locOffsetY;

    // Loop through loaded tiles(x/y tile coord)
    for (int x = (int) (Math.floor(cameraX) - (screenWidth / 2)); x < Math
            .floor(cameraX) + (screenWidth / 2); x++) {
        for (int y = (int) (Math.floor(cameraY) - (screenHeight / 2)); y < Math
                .floor(cameraY) + (screenHeight / 2); y++) {
                            // The screen-relative tile coord
            int sx = (int) (x - Math.floor(cameraX));
            int sy = (int) (y - Math.floor(cameraY));

                            // Tile pixel location
            int locX = sx * TILE_SIZE + offsetX;
            int locY = sy * TILE_SIZE + offsetY;

            // Draw box/location info
            g.setColor(Color.RED);
            g.drawRect(locX, locY, TILE_SIZE, TILE_SIZE);
            g.drawString(x + ", " + y, locX + 10, locY + 20);
        }
    }
}


texts: Implementing character movement using real physics

texts:
This is the first time I'm seriously developing a game so apologies if I'm missing the obvious.

In my 2D platformer I adopted Box2D since it seemed like a natural solution to model gravitational pull (player dropping off platforms) and jump arcs and in the process get collision detection for free. It was also a breeze to integrate with libgdx which I'm using as the main game engine.

One thing that I'm struggling with though is, ironically, the most simple thing: expressing player movement along the x axis using Box2D. Where previously it was as simple as translating position as a function of time, now I can only indirectly affect player position by applying a horizontal force to the rigid body representing the player, thus increasing its velocity.

I have multiple problems with this approach:

If I add friction to the platform fixtures, which seems natural, the user has to keep applying a force to the player for it to keep moving. However, my input system is based on the user pointing to a target platform or block upon which the character moves there, then stops.
If I remove the friction from any static objects the player steps on, then it's sufficient to apply force force once for the player to keep moving, but how do I tell it to stop at point x? I couldn't come up with a solution that does not feel convoluted or unnatural. I was thinking for instance to store the target position and then apply a balancing force in the opposite direction once the player reached it. Sounds complicated and prone to failure in corner cases though. I also thought about placing invisible geometry one unit ahead of the target position so that the player would collide with it and stop once reaching the position.

But seriously, both ideas sound complicated and kinda dumb. Am I missing the obvious?

I'm thinking already that maybe I should pursue a mixed approach of physics and direct controls, but I already tried that and Box2D does not like it if I set object positions manually, since this short circuits the computations behind the scenes?


texts: As a direct result of this question that I asked a few days ago, I want to draw potentially-complex geometry to a SDL_Texture or, I suppose, an SDL_Surface. Ultimately, I want the foreground of a 2D platformer on this texture so that I cant draw a specific portion to the screen, as explained in the above link. Most of the geometry will be simple rectangles, but I would also like to draw slopes and possibly circles. Diving into OpenGL seems like a viable option at this point, but if I could avoid it, that would be grand.


texts: How can teams collaborate on Unity 3D projects?

texts:
With a friend of mine, we are planning to develop a small game to get the hang of game development and teamwork. But since Unity 3D barely supports version control (or at least the free version lacks of it) we have no idea how to efficiently manage teamwork. Sharing tasks in a small project is also seems like a challange for us.

I would also appreciate any advice that could be useful for beginner indie developers related to teamwork. :)


texts: Proper way to load assets with a FSM transition between menus and actual game

texts:
So far I am making a game in C++ and SDL, and the way to switch between the different menus and the actual game is via a Finite State Machine, AKA a stack where I put each state (MenuState, GameState...) on top, and only render and update the top of said stack.

Now I need to load assets such as images, and I am thinking of creating a class for each state which will hold all the address of the textures, sound, etc and pass it to each state so that it can render, play sound, etc, properly.

Something like a GameAsset class that I pass to GameState(GameAsset ga) when I create one, so that GameState::render() can do its work fast.

Is there any better way (easier to implement, faster, whatever) to do this ? It seem like it's stretched out for me, as I haven't made games on this scale before. Will this become unmaintainable or whatever ?

Thanks.


texts: Fast 2D collision detection in an unbounded space

texts:
I'm trying to do collision detection on a large number of entities of greatly varying size in an unbounded space.  The entities are circles, so it's relatively easy to check if two are colliding.  However, with a large number of entities the simulations slows down a lot when I code it to check every entity against every other (for n entities, I believe it is n*(n-1)/2 checks, way too many!)  Here's my though process so far:

First, I considered using a grid of some sort, like described in steps 1-2 of the answer here: Fast, accurate 2d collision

There are, however, a few problems with this:

1) It is an unbounded space.  Where do I start and end the grid?  How do I determine the size of each square in the grid in a world where some objects are literally tens of millions times larger the other objects?

2) Even if I somehow manage to adjust the size of the grid every frame without using too much processing power, so that it adjust to fit the most distant objects, (unlikely that I could do this efficiently) this is still not a solution.  If tons of objects are clustered in a 10,000x10,000 space, and one object goes shooting off into space 100 billion units of distance away, the grid would "zoom out", leaving all of the objects in the smaller 10,000x10,000 space in one square, which would defeat the purpose of making a grid in the first place.

For these reasons, I'm thinking that a simple grid is not the best idea...

I looked at BSP's, and I admit that I don't fully understand the concept, but it seems like it does not apply well to my situation (especially since I am using circles and BSP seems better suited to a more complicated polygonal world).

Quad trees seem promising (something like this perhaps: http://www.youtube.com/watch?v=qJJnzSLrC1E) but I foresee at least two potential issues:

1) I can calculate the "farthest away objects" each frame to give calculate GreatestXValue, LeastXValue, GreatestYValue, and LeastYValue, for each frame. From that I have a rectangle to work with that contains all entities.  However, I will have to redo this each frame, which means that I have recreate the the entire quadtree each frame: no shortcuts on calculations done in previous frames.  Is this a problem or do most game/simulation programmers have to completely recreate the quadtree each frame anyway?

2) (Probably the bigger problem) How do I handle a massive object in the vincinity of many small objects? Think about many circles with radius 5 being very close to, resting against, or colliding with a circle with radius 100,000. That massive object will be in many, many grid squares, and it seems to me that the situation would force the creation of a tree that is far too broad and deep.

Am I on the right track with my thought process? Where do I go from here?  Thank you very much for your time and help!!


texts: translate-scroll repeated 2d texture using opengl shader

texts:
I managed to implement an infinite 2d texture scrolling using the following shader. btw I'm using cocos2d-x 2.2.1.

The vertex shader:

attribute vec4 a_position;
attribute vec2 a_texCoord;

#ifdef GL_ES
varying mediump vec2 v_texCoord;
#else
varying vec2 v_texCoord;
#endif

void main()
{
    gl_Position = CC_MVPMatrix * a_position;
    v_texCoord = a_texCoord;
}

The fragment shader:

#ifdef GL_ES
precision lowp float;
#endif

uniform vec2 u_time;
uniform vec4 u_color;
varying vec2 v_texCoord;
uniform sampler2D CC_Texture0;

void main()
{
        gl_FragColor = texture2D(CC_Texture0, v_texCoord + u_time);
}

But once I try to add some uniform color the texture is no more repeated correctly (and performance decreases drastically):

/// Texture not repeated correctly and performance degradation
gl_FragColor = texture2D(CC_Texture0, v_texCoord + u_time) * u_color;

However the following repeat the texture correctly (but of course there's no scrolling)

gl_FragColor =  texture2D(CC_Texture0, v_texCoord) * u_color;

What am I doing wrong?


texts: cocos2d - exclude GUI layer transformation

texts:
I have a game layer that should be pannable and pinchable and a GUI layer as an overlay that's excluded from the transformations. I added the pinch and pan gesture recognizer to the view and set the view.transform like so

view.transform= CGAffineTransformConcat(panTransformation, pinchTranslation);

But it actually scales/moves the GUI layer, ofcourse, as it is a layer added to that view aswell. Sure I could do the transformations the layer itself, but the touch coordinates are scaled aswell, and calculating where the user actually tapped based on scale and translation looks like a big overhead to me.

Can I somehow add a separate view and make a GUI layer it's child? Or in any other way add GUI layer that's excluded from the transformations ?


texts: How can glass breaking effect from Smash Hit be achieved?

texts:
I saw Smash Hit the other day and was amazed by the physics of the game, specially the shattered glass effect:

I've read other posts about this subject but I still feel that they don't share enough details to let me get started on implementing this on my own with OpenGL/GLSL.

Is it possible for somebody with an enhanced perception and graphics understanding to watch the gameplay and give some pointers on how this effect could be replicated?

I rather not use 3rd party physics engine and do the entire thing on my own for educational purposes, so could you mention some of the physics that goes behind this as well?

References to other documents and demos are highly appreciated.


texts: UI/Menu that works with and without VR (Unity, WMR)

texts:
I'm working on an app that I want to be useable without and with VR (with a Windows Mixed Reality HMD like the Samsung Odyssey).

For non-VR I'm simply using a canvas in "Screen Space - Camera" and a second camera, which is a child of the Main Camera and can only see the UI (the Main Camera can see everything but the UI). This way the menus are displayed as transparent overlays that are always visible to the player (with the game scene in the background).

For VR you have to use World Space. This makes sense because I want to be able to look around without having the menu move too.

How do you now make an e.g. pause menu work in VR AND non-VR - depending on if the player plugs in his headset before starting the app or not?

Do you change the Screen Space to World Space in code at runtime if there's an HMD?
Do I have to move the whole canvas at runtime to where the player is? You'd want the menu to be in front of the player, no matter where he is but it also has to be in front of the other objects in the scene, so you can interact with it.

I'm using Unity 2017.3 with OpenVR/SteamVR.


texts: Tell Unity to use a certain LayerMask to raise or not OnDrop (for a class that implements IDropHandler)

texts:
I am trying to make a draggable GameObject that can be dropped within a container but when i'm releasing the mouse button even though the mouse is over the container (and the dragged object too) OnDrop isn't raised on my container. To make it work i must pick the dragged GameObject right at its edge so that the mouse is over the container but not the draggable when i release the mouse button

According to what I've seen drag and drop handled by unity is based on Raycasts and Raycasts could be configured to ignore objects that are in certain Layers thanks to a LayerMask the problem is that i wasn't able to find anything to apply a LayerMask

Is there a way to do this or any workaround that could let the drop target know that a dragged was dropped on him?


texts:
In Panda3d, I load a model and place 10000 references to it in the scene-graph.  It runs at (say) 2Hz.

I load a 3d model containing 10000 copies of that exact same object, and it runs at (say) 60Hz.  As does using the flattenStrong() command which is effectively the same thing but at runtime.

So the question is: is this behaviour a peculiarity of Panda3d, or is it a fundamental law which applies to all games engines?


texts: Creating an isometric map with hexagonal tiles for iPad

texts:
I'm new to game development, so I need a little help.

I have to write down a little game which has a floor with hexagonal tiles, but it must be seen in an isometric view like The Sims.

Ignoring the UIKit way, I used CoreGraphics method and I managed to draw a hexagonal map and to get it working but this only in the orthogonal view.

Hoping that Cocos2D could help me, I've studied a little, but I only see that the hexagonal maps are supported only in orthogonal mode. In the stackoverflow community, someone who understand about that much more than me, told me that I simply cannot draw it with Cocos2D tiles, so, thinking at this image:

http://www.issamtp.org/gnfGr.jpg

I guessed that there must be another way, which I hope is not to calculate the "skew" manually.

The nearest results I managed to obtain were with CAAffineTransform which doesn't give the depth effect seen in the image above (at least I didn't managed to give it) or with CATransform3D without perspective.

Can someone tell me if I'm in the right way, and if so, how should I set the parameters of the Transform matrix to get the desired effect?

EDIT:

Here's the code I used

sfondo = [[Sfondo alloc] initWithFrame:CGRectMake(sfondoX, sfondoY, sfondoWidth, sfondoHeight)];
/*sfondo = [[Sfondo alloc] initWithFrame:CGRectMake(200, 200, 300, 300)];*/
[sfondo setBackgroundColor:[UIColor clearColor]];
[sfondo setDelegate:self];

CGAffineTransform transform = CGAffineTransformIdentity;
transform.b = 0.5;
transform.a = 1;
sfondo.transform = transform;


texts: I am very interested in a career as a video game designer. to clarify i mean one of the people to figure out how the mechanics, story,  levels and art all work together. To any designers on the website what post-secondary education should I look for? I know that typically they have knowledge of all different parts of game development but is there anything specific I should be looking for that would helpful as a base?


texts: Calculating complex D&D style interactions

texts:
So I don't even know if this is the right community to ask (as I imagine it's probably quite maths heavy) in but I figure it falls under the realm of game mechanics.
I want to develop a game mechanic that utilises complex D&D style interactions but on another level from that, but I don't really know where to begin conceptually. What I mean by D&D style interactions is each character will have a set of attributes, strength, skill, intelligence etc and those attributes will dictate how interactions play out between characters.
So for basic example, two characters battling each other and each attribute ranges from 0-20.
Character A - Attack:13, Defence:14
Character B - Attack:15, Defence:10.
So when Character A strikes at Character B I need to calculate how successful that attack would be and what the outcome would be, which would then feed back into their attributes. So maybe their attack is semi-successful and produced a flesh wound, not enough to kill but that reduces Character B's Attack attribute to say 13.
Now that's a fairly trivial, example where I want to try and take it to the next level is to introduce combined attributes that all have an impact on the outcome of a move. So Skill, Experience, Fitness, Attack Speed, Anticipation and even Luck (which I figure would be randomised and offset by attributes like Experience).
Ideally I'd like to build an engine where I can define attributes and how they interact and can add more over time to build up the complexity of interactions. But I am at a loss where to begin. I'm not looking for a ready made solution but just to be pointed in the right direction.
To add some further explanation as to where I'm struggling. Are there known algorithms, techniques or maths solutions that are used to calculate attribute based interactions? In my head I'm imagining some system of values and weights with some pseudo-randomness thrown in but I'm at a loss as to how you actually calculate outcomes.
When I try and think it through all I get is a massive set of 'if' statements where values go in at the top, if's are applied and modify the outcomes. So...
If CharA_Attack == 15 and CharB_Defence = 10 Then Outcome = Kill

If CharA_Speed == 10 and CharB_Speed = 12 Then Outcome = Deflected Blow

If CharA_Luck == 14(random) and CharB_Luck 7(random) Then Outcome = Flesh Wound

Etc...