texts:
This is a follow-up question to my previous question. I got my key holding to move, using boolean variables and making another method with a javax.swing.Timer for delays(Thank you to KingDolphin), but strangely when I move my Icon it seems to increase how many pixels it moves each time by 1. It moves one pixel the first keyPressed, then two for the next, then three, etc. This may not seem like much, but when you are moving by 30+ pixels, it gets out of control. I really have no Idea how to fix it. I have tried changing some things, and I have "done my homework"(Googled and searched StackExchange sites including this one and StackOverflow), but have found nothing even related to it. Here's my layoutGame and move methods(The problem is in there), and thank you for helping me out:

    private void layoutGame() {
        JLabel title = new JLabel("Dodge The Enemies!");
        Font titleFont = new Font(Font.SERIF, Font.BOLD, 32);
        title.setFont(titleFont);
        title.setHorizontalAlignment(JLabel.CENTER);
        title.setBackground(Color.BLACK);
        title.setForeground(Color.WHITE);
        title.setOpaque(true);
        add(title, BorderLayout.NORTH);

        JLabel background = new JLabel();
        background.setIcon(backDrop);
        add(background, BorderLayout.CENTER);

        JLabel you = new JLabel();
        you.setBounds(x, y, 50, 50);
        you.setIcon(new ImageIcon(this.getClass().getClassLoader().getResource("happy.png")));
        background.add(you, JLabel.CENTER);

        JTextPane direction = new JTextPane();
        direction.setText("Direction");
        add(direction, BorderLayout.SOUTH);

        direction.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if(e.getKeyChar() == 'w') {
                    wPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 'a') {
                    aPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 's') {
                    sPressed = true;
                    move(you);
                } else if (e.getKeyChar() == 'd') {
                    dPressed = true;
                    move(you);
                }
                direction.setText(null);
            }
            public void keyReleased(KeyEvent e) {
                wPressed = false;
                aPressed = false;
                sPressed = false;
                dPressed = false;
            }
        });
    }

    private void move(JLabel icon) {
        int delay = 100; //milliseconds
        ActionListener taskPerformer = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (wPressed) {
                    y = y - 1;
                } else if(aPressed) {
                    x = x - 1;
                } else if(sPressed) {
                    y = y + 1;
                } else if(dPressed) {
                    x = x + 1;
                }
                icon.setBounds(x, y, 50, 50);
                icon.repaint();
            }
        };
        new Timer(delay, taskPerformer).start();
    }


texts: Godot 3.X Implementing a smooth movement for pitch, yaw & roll

texts:
I'm implementing pitch, yaw and roll on airplane object, but when rotating the object (either pitch, roll or yaw), it starts rotating slowly but then the rotating movement goes awfully fast very quickly.
it's quite jarring. i'm not sure how to make more smooth.
The issues:

I think the problem lies in the acceleration when the object rotates, i want to be an uniform speed
Other problem from this code, it's that if want to change the rotating direction it's slow to change, takes a while to rotate to the opposite direction

The player input code:
extends Node
const MAX_CAM_ANGLE = 30
var pitch_dir = 0
var yaw_dir = 0
var roll_dir = 0
var thrust = 0.5
var input = ''
func _ready():
    $DebugStats.add_property($Plane, "transform:origin", "round")
    $DebugStats.add_property($Plane, "force", "round")
    $DebugStats.add_property($Plane, "torque", "round")
    $DebugStats.add_property(self, "pitch_dir", "round")
    $DebugStats.add_property(self, "input", "")

func _physics_process(delta):
    process_inputs(delta)
    process_movement(delta)

func process_inputs(delta):
    if Input.is_action_pressed("p1_fire"):
        $Plane.fire_weapon()
        input = 'fire'
    if Input.is_action_pressed("ui_up"):
        thrust += delta
        input = 'accel'
    if Input.is_action_pressed("ui_down"):
        thrust -= delta
        input = 'slow'
    if Input.is_action_pressed("p1_pitch_up"):
        pitch_dir += delta
        input = 'up'
    if Input.is_action_pressed("p1_pitch_down"):
        pitch_dir -= delta
        input = 'down'
    if Input.is_action_pressed("p1_roll_left"):
        roll_dir += delta
        input = 'yaw left'
    if Input.is_action_pressed("p1_roll_right"):
        roll_dir -= delta
        input = 'yaw right'
    if Input.is_action_pressed("p1_yaw_left"):
        yaw_dir += delta
        input = 'yaw left'
    if Input.is_action_pressed("p1_yaw_right"):
        yaw_dir -= delta
        input = 'yaw right'

    if Input.is_action_pressed("ui_quit"):
        get_tree().quit()

#TODO Adjust values to make movement more smooth
func process_movement(delta):
     thrust = clamp(thrust, 0.2, 1)
     pitch_dir  = clamp(pitch_dir, -.6, .6)
     yaw_dir  = clamp(yaw_dir, -.6, .6)
     roll_dir  = clamp(roll_dir, -.6, .6)
     $Plane.calc_force(thrust, pitch_dir, roll_dir, yaw_dir)

The plane movement script:
extends RigidBody

const v3 = Vector3(0, 0, 0)
const scalar_z = Vector3(0, 0, -1)
var force = v3
var torque = v3
var drag = v3
var lift = v3
var thrust = v3

const MAX_THRUST_TURN = 150
const MAX_THRUST = 1  # temporal value just to debug the rotating problem
const MAX_CAM_ANGLE = 30
const DRAG_CONST = 1 # temporal value just to debug the rotating problem

# Calculates flying speed and direction
func calc_force(thrust, pitch_dir, roll_dir, yaw_dir):
    var speed = MAX_THRUST * (thrust)
    var drag_coef = DRAG_CONST / MAX_THRUST / MAX_THRUST
    thrust = transform.basis.z * (-speed)
    drag = transform.basis.z * drag_coef
    lift = transform.basis.y * drag_coef

    force = thrust + drag + lift
    var pitch = global_transform.basis.x * pitch_dir * MAX_THRUST_TURN
    var yaw = global_transform.basis.z * yaw_dir * MAX_THRUST_TURN
    var roll = global_transform.basis.z * roll_dir * MAX_THRUST_TURN
    torque = pitch + yaw + roll

# Applies all force at once in the airplane object
func _integrate_forces(state):
    add_central_force(force)
    add_torque(torque)

How i can make the rotating movement more smoother?
Note: this is an arcade game, not really interested in a complex solution for the physics.
Note 2: if you want to test it, you can check out here
https://github.com/balmeidaa/godot_sky_aces


texts: Hey guys I have experimented in making games in java.  So far I have created A text game in JOptionPane that is kind of like Zork but with yes and no buttons (that were changed to "left" and "right").  I have also made a small game  where a ball bounces around a screen but with was with heavy help from a website tutorial.  Do you guys have any advice or stories about your first game programming? I really want to get into it but it seems like such a steep learning curve.  Any help on where I should start or advice? Thanks guys!


texts:
Please can somebody help me as I'm a lil bit new to game dev and user interface designing.
I am trying to create a simple Texas holdem poker using phaser3 for multiplayer application.
I have a few doubts this is my app.js

   const config = {
  type : Phaser.AUTO,
  width : 800,
  height : 600,
  backgroundColor : #000000,
  physics : 'arcade',
  scene : {
    preload : preload,
    create : create,
    update : update

},
}

var game = Phaser.Game(config);

What is actually happening in this code and what should be my project folder structure for any simple multiplayer online game.
Can I set the witdh and height dynamically depending on the device width and orientation??.

Please anybody who could just explain me a few things about gamedev...

Thanks in advance.


texts: Is there an OgreXML model viewer for Linux? I know about OgreMax but apparently that's Windows only.


texts: Godot 3.2 Bomb explosion doesn't affect player or npc

texts:
I finished the Godot 2D game tutorial Dodge the Creeps, and i'm adding a few additional features to reinforce the things learned and make more interesting the base game.

Basically i added a Scene with a area2d as root node with a collisionShape2d,a 2 timers for the Bomb scene.

The bomb appears randomlly in the main scene, for a few seconds is supposed to be ticking and then explodes.

My problem is that neither the player or the creeps( the npc enemies) are being removed from the scene.
They don't interact at all,

This is the code for the Bomb.tscn scene:

extends Node

func _ready():
    # Area collison disabled until animation finishes
    $CollisionShape2D.disabled = true
    # Bomb ticking animation
    $AnimatedSprite.animation = "bomb"
    # Until BombTimer times out we change animation and activate collisionArea
    $BombTimer.start()

func _on_BombTimer_timeout():
    # Change animation sprite
    $AnimatedSprite.animation = "explosion"
    # Enable Collision area
    $CollisionShape2D.disabled = false
    # Start timer to remove bomb object
    $RemoveTimer.start()

func _on_RemoveTimer_timeout():
    queue_free()

The code for the creep/mob when hit by the bomb:

func _on_Mob_body_shape_entered(body_id, body, body_shape, local_shape):
     $CollisionShape2D.set_deferred("disabled", true)
     queue_free()

The code for collision detection for the player when is hit:

func _on_Player_body_entered(body):
     hide()  # Player disappears after being hit
     emit_signal("hit")
     $CollisionShape2D.set_deferred("disabled", true)

If the creep/mob touches the player the game is over, but if the bombs explodes nothing happens.
What i'm missing in the code?


texts:
I'm creating a multiplayer online trading game. The things that are traded range from raw items to complex products. For example Steel is a raw item. Mechanical Assembly is a more complex item that requires 2x Steel and maybe 1x Rubber. Then Hydraulics is an item that contains 2x Mechanical Assemblies and 1x Electronics (which is another complex item). So and so forth.

These items will be created by me, players can't create their own items, so it doesn't need to be able to handle arbitrary layers of complexity for items.

If my example isn't clear, think Minecraft. You have wooden planks, which can be made into sticks. From there the sticks - combined with metals - can be made into tools. My game is nothing to do with minecraft or any sandbox building game, but it uses a similar progressive complexity to creating items that I want to have in my game.

My question is basically, how do you store something like this assuming that I will want to add more items in the future? Do you store it in a database or in a seperate library that the game uses?

EDIT

None of the items actually "do" anything, they are simply there to either sell, purchase, or combine with other items to make a more complex item, which can then be sold, purchased or combined... you get the idea. The items themselves would not have any properties, but the instances of the items would. For example an item that one player has would have a certain "quality" and if they were selling it a certain "price". An instance of that same item that a different player had would need to have a different "quality" and "price" if they were selling it.

I think the price part will not be required on an individual item because instead I would have a "sale" object which was for a price and contained certain items.


texts:
One thing that always stop me when I want to start making a game is having no idea what to do. How do people get ideas for their game ? I mean realistic ideas for people who are alone with the minimum ressources (no money for assets, blender and unity). I will never stop being impressed by all new concept, mecanics or crazy ideas of game indie developpers come-up with, like making game out of random everyday objects. I wish I was able to do that.
Do developpers get their inspiration by looking at other games and trying to mix them or change the concept ? Do they look outside trying to come up with what they wish was a game ? Or do they simply walk around and try to imagine a game with whatever they see or reallife situations or concept ?


texts: Alternative to 2D array in a tiled-map structure

texts:
After searching for a long time, I'm surprised this question was not asked yet. In a 2D, tiled-map game, how do you handle the map ? I'd be glad to have your point of view in any languages, though I'm more interested in C++ implementations.

A 2D array, a 2D vector, a class handling a linked-list with ad hoc computing to handle coordinates, a boost::matrix... ? What solution do you use and why ?


texts: How can I randomly generate 2D tile-based side-scroller terrain?

texts:
I want to randomly generate a map for a 2D sidescroller game using the following tileset:

I have found a few great articles on the bitmasking process, for example:
http://www.angryfishstudios.com/2011/04/adventures-in-bitmasking/
http://www.saltgames.com/2010/a-bitwise-method-for-applying-tilemaps/

I like the idea of using a bitmask/tilemask instead of doing a huge if clause or switch statement.

However, I am having trouble visualizing the entire process and none of these articles talk about randomizing.

My tiles fit together in multiple different ways, not just one way as the tiles in the examples I linked seem to.

For example here are just a few examples:

Since my tiles fit together in many different ways I don't think an 8 bit mask will work.
Therefore, I was thinking of using a larger bitmask. Something like char[8] or char4.

If someone could please show some pseudocode/examples of how the general algorithm would look, I would greatly appreciate it.


texts: What advantages does DirectX 11 have over DirectX 10?  Most of the new features seemed to be for directcompute from what I can tell, and how much more are you limiting your market by if you use DX11 compared to DX10 (assuming you don't add DX10 support).


texts: How collisions should be handled in terms of design

texts:
I'm not sure how should I design the collision part in order to respond the all the game requests.

First that comes in mind is
1. Update the game objects positions
2. Check the collision
3. Update the positions based on collision data

Now the problem is what if an object needs to know when it did collide in order to perform some actions.
Lets say a player picks a chests, so he must not be bounced by the chest and also all the player, chest and cut scene sequence need to be triggered.

So if I do everything in collision routine (without triggers) then all the game logic is biased toward one game and is not flexible, its need to be adapted/rewritten for each game.

If I use triggers and call every object collision function what if player needs to move backward and collisions needs to be rechecked, do I need to make a flag to recalculate and collisions for objects that has this flag set until collisions are done?

Or do I check for chest collision in player update method (before the global collision routine) and do all the calculations there... but what if I don't want the player to react to collision if chest is closed and react if its opened (not just a player-chest collision pair setting)?

What is the best way to implement this kind of system that will be flexible for future games and in the same time respond to all requests of game design (in this case the example I wrote above, player-chest)


texts: Design patterns for live coding/script reloading

texts:
I would like to make C++/Lua combo and write scripts for a game with live script reloading. What design patterns should I be aware of so not to cause me unnecessary pain?

For example if I have a simple MUD game with enemies and maps, I can bind a Lua function which would remove all the enemies and recreate them based on the data(which I would modify with Lua script).

That sounds easy, but haven't done so I think there may be some deadends without proper planning.

What are the best design patterns and solutions for live script reloading?


texts: Instantiate random different gameObjects in specific spaces?

texts:
I need to instantiate different gameObjects of different shapes and sizes on top of the left third and the right third of a table, and all this objects need to be random every time the scene loads. I have a library of around 80 GO but the most I'll instantiate, for now, is 30. All the instantiated GO have to be different, that means no duplicates.
I thought that maybe I could create 30 empty gameObjects on the table, where I want to instantiate them in random, but I'm not sure if this is the most intelligent way to do it. Is there any other way?
Also, since I have a library of GO so large, would it be possible to load the folder in the script instead of defining a list and populating it in the editor?
I'm a bit new at coding for Unity, but I'm an experienced programmer.


texts: ECS: performance of many systems cycling on entities

texts:
I have been working with an ECS for my current game and I noticed that I came up with quite a few systems that go over lists of entities that sometimes overlap, so it's not unlikely that I loop on the same entity more than once as more than one system is processing that same entity.

Wouldn'it it be better to just iterate once over all th entities that should be updated instead? And if so, how would you do that? Redesign the systems so that a single system is in charge of more stuff on the same entities? Move the code from systems to an update() method on the components?
Or am I just worrying about something that isn't really going to have a big impact on performances compared to other bottlenecks that could arise from taking a different approach?


texts:
It is possible to implement fragment shader to do one-pass gaussian blur?
I have found lot of implementation of two-pass blur (gaussian and box blur):

http://callumhay.blogspot.com/2010/09/gaussian-blur-shader-glsl.html
http://www.gamerendering.com/2008/10/11/gaussian-blur-filter-shader/
http://www.geeks3d.com/20100909/shader-library-gaussian-blur-post-processing-filter-in-glsl/

and so on.

I have been thinking of implementing gaussian blur as convolution (in fact, it is the convolution, the examples above are just aproximations):

http://en.wikipedia.org/wiki/Gaussian_blur


texts: How to delete Unity Hybrid ECS Entities?

texts:
I'm trying to get into Unity's Hybrid ECS feature. Creating and Manipulating Entities has worked fine so far for me, but somehow I can't find a viable option to delete Entities which works 100% of the time without errors.

I know about object pooling, however in this particular case there is no way around deleting Entities.

Thank you in advance!


texts:
I want to draw cone using OpenGL ES  I have gone through many links to draw cylinder but I don't have any idea or approach to draw the cylinder. I've seen the gluCylinder function for OpenGL, but no equivalent function in OpenGL-ES.

i tried the below code

float radius, halfLength;
int slices;
for(int i=0; i<slices; i++) {
    float theta = ((float)i)*2.0*M_PI;
    float nextTheta = ((float)i+1)*2.0*M_PI;
    glBegin(GL_TRIANGLE_STRIP);
    /*vertex at middle of end */ glVertex3f(0.0, halfLength, 0.0);
    /*vertices at edges of circle*/ glVertex3f(radius*cos(theta),
    halfLength, radius*sin(theta));
    glVertex3f (radius*cos(nextTheta), halfLength, radius*sin(nextTheta));
    /* the same vertices at the bottom of the cylinder*/
    glVertex3f (radius*cos(nextTheta), -halfLength, radius*sin(nextTheta));
    glVertex3f(radius*cos(theta), -halfLength, radius*sin(theta));
    glVertex3f(0.0, -halfLength, 0.0);
    glEnd();
}


texts:
I have a function in my JS that gets the user's mouse click on the canvas.

Now lets say I have a random shape on my canvas (really its a PNG image which is rectangular) but i don't want to include any alpha space.

My issue lies with lets say i click some where and it involves a pixel of one of the images. The first issue is how do you work out the pixel location is an object on the map (and not the grass tiles behind).

Secondly if i clicked said image, if each image contains its own unique information how do you process the click to load the correct data.

Note I don't use libraries I personally prefer the raw method. Relying on libraries doesn't teach me much I find.


texts: How can I implement temporary effects in Objective-C?

texts:
How could I use this IBAction

-(IBAction)shield:(id)sender{
    appDelegate.healthInt = 150;
}

and simply make it work for a limited time. I want to set appDelegate.healthint = 150 for about 20 seconds. I'd assume this works with some sort of NSTimer. Not really sure. I'm not using any frameworks.


texts: i'm going to describe what need to be done... "there are circular areas marked in a map, large areas a person can easily move in to them and out of them" what i'm trying to do is deciding weather the person is moving in to or moving out of that circular area. i can get the user location and see weather it falls inside the circle(weather the person is inside the circle) by pure mathematics theories(theories of circle), but how can we decide weather the person in moving in to the circle or moving out of the circle? please give me some advice guys?


texts: How to reduce/handle image loading times?

texts:
I'm working on a 2D game that has very high resolution images (so that things look good on Retina MacBooks and such), and am seeing a noticeable lag caused by image loading.

I notice the strongest lag when I switch to a screen that loads 72 500x600 PNG images - it takes almost a second on a pretty modern system with an SSD. Loading the files from the disk is fairly quick, usually less than one millisecond. But loading the PNGs takes about 5-7 milliseconds each, using libpng.

Now I have two questions:

What are my options for speeding up the loading?

Will using sprite sheets help? (My guess is no, since loading times seem to increase with image size).
Would it make sense to add pre-downscaled versions of the files and use these on lower resolutions?

Should I load all assets upfront?

My current approach is a bit naive: Each entity loads its own texture as soon as it is instantiated. I can change things a bit to make sure all entities are instantiated upfront where possible, but that seems error prone.

Are there better approaches? I think we'll end up with around 100-200 MB of images, so it might be fine to load them all into memory when the game starts. The best approach I can come up with is to have a huge mapping from image files to image IDs and use the IDs to load images in the code - then I'd know all the image files upfront. Or should I shy away from loading everything upfront if I can speed the loading up until it's unnoticeable again?


texts: How can I implement fixed joints in a 2D physics system?

texts:
I'm developing a simple, 2D physics system to complement an entity/component game object framework. So far, I have implemented some basic, tutorial-level physics. An entity that is affected by physics must have two components:

Transform (translation, rotation, scale; may have parent transform)
Rigidbody (mass, list of forces)

The physics engine currently uses Verlet integration to move entities - that is, velocity is derived from the current and previous positions of an entity, and is not explicitly stated anywhere.

I would now like to start implementing some joints, starting with the basics and perhaps expanding as I grow more familiar with the concepts.

The first joint I attempted to implement was extremely simple - the fixed joint, whereby two entities are 'fixed' together and their transforms may not change relative to each other. My approach was to make one entity an immovable child of the other - that is, to set the transform of A as a local transform relative to B and disable movement of A by passing all accumulated forces of the rigidbody of A to the parent, B. Already this seems hackish and inflexible and has issues with gravity (B ends up with two gravity forces acting on it) - I'm clearly heading in the wrong direction.

I have searched for some literature on the subject but have only found either very basic tutorials that only cover what I've already done, or articles with advanced mathematical formulae that are difficult to follow or relate to simulation in any meaningful way.

This leads to two questions:

How are fixed joints normally implemented?
Are there any good 2D physics simulation tutorials aimed at those without a degree in physics or mathematics?


texts:
I am trying to work out the best way of implementing a camera in my simple 2d game.

The way it is structured at the moment is my game objects all have draw functions, which are passed a canvas instance to draw themselves to (at whatever position they are currently at).

I now need to add a camera to the mix, so that i can have a bigger world, but i'm not sure of the best way to implement it.

The way I see it, I can either translate the whole canvas and let the objects carry on drawing themselves at whatever position they are at, eg:

canvas.translate(camera.position);
player.draw(canvas);

This seems easy enough, but doesn't seem right somehow. Alternatively, I could pass the camera in to the objects with the canvas, and let the objects calculate a relative screen position before drawing, eg:

player.draw(canvas, camera);
// inside the draw function:
var position = this.position.subtract(camera.position);
canvas.drawStuff(stuff, position);

But that seems wrong too. How do other 2d engines handle this? Is there an established best way of doing it, or any pitfalls I should avoid?


texts: Converting from different handedness coordinate systems

texts:
I am currently porting a demo from XNA to DirectX which, as I understand it, both have coordinate systems with different handednesses.

What are the things I need to bare in mind when converting between the two? I understand not everything needs to be changed.

Also I notice that many of the 3D maths functions in some of the direct3D libraries have right handed and left handed alternatives. Would it be better to just use these?


texts: When I start running, it won't stop when I let go of shift. Why?

texts:
Following is my code, and after I let go of shift the image speed goes back to normal but not the variable I created called movespeed. What should I add or change to fix it?

//Run with left shift
if (keyboard_check(vk_lshift))
{
     movespeed = 5;
     image_speed = 0.14;
}


texts: How to implement a mechanic of entering a town

texts:
I am planning a game played on a 2-D map, where some spots are "towns". When the player walks into a town, he enters a high-resolution map of this town; when he exits the town, he returns to the low-resolution map of the world (as in e.g. Ultima 4). My question is how to implement this enter/exit mechanism in Unity? I thought of two approaches:

The world map and each of the town maps is a different scene. Entering/exiting a town is implemented by loading the appropriate scene using the scene manager.
There is a single scene, but the maps are geographically separted. For example, the world map is in coordinates 1...256, town A map is in coordinates 301...364, town B map is in 401...464, etc. Entering/exiting a town is implemented by moving the player and the camera to the appropriate map.

Is there a better approach? What approach is commonly used to implement this mechanism?


texts: 2.5D platformer how to darken building edges?

texts:
I was wondering how I could go about creating a vignette type effect / some sort of volumetric shadow for the 'cross section' parts of a 2.5D level. The effect I'm going for can be seen in 'This war of mine' where the edges of the rooms and walls / floors that are facing the camera have been darkened and blurred. (see below).

I thought about creating the edges in photoshop and then blurring them and putting them in, however the blur scales weirdly as I'm re scaling the sprites so it looks really fake and not like a visual effect. Is there perhaps a 2d shader I could use or make?

Any help on this would be appreciated!

Cheers

My photoshop attempt to recreate


texts: Why is SpriteBatch.end() generating null pointer exception in this code?

texts:
I am getting a null pointer exception using libGDX that the debugger points as the SpriteBatch.end() line. I was wondering what would cause this.

Here is the offending code block, specifically the batch.end() line:

    batch.begin();

    for (int j = 0; j < 3; j++)
        for (int i = 0; i < 3; i++)
            if (zoomgrid[i][j].getPiece().getImage() != null)
                zoomgrid[i][j].getPiece().getImage().draw(batch);

    batch.end();

The top of the stack is actually a line that calls

lastTexture.bind();

In the flush() method of com.badlogic.gdx.graphics.g2d.SpriteBatch.

I appreciate any input, let me know if I haven't included enough information.


texts: Efficiently calculating best nearest sphere from a point in 3D space

texts:
I have a point in 3D space and a number of spheres (anywhere from 0 to thousands) at random locations in said space.

Each sphere has a property that falls off in a smooth gradient from the centre to the edge.

The point could be inside between 0 and all of the spheres.

How do I calculate the sphere that the point is inside that has the highest 'value' at its current position?

I was wondering if I could get away with just looping through every sphere and adding the ones the point is inside, then looping through those and testing the value. However, the calculation for this needs to be calculated 'instantly', or at least with minimal delay, so I'm wondering is that is too inefficient.


texts: Is there any Lua API that works with C# for PC & XBox 360 Development?

texts: I am reading a book on Game Development in which they show you how to make scripts for your game in Lua. They program Lua and use it from C++, but I was wondering if there is a library or API to use Lua from C#: specifically from XNA to develop games for PC and XBox 360?


texts: When to stop taking items from ever-growing queue and start processing them?

texts:
I am developing a fast-paced multiplayer shooting game and following instructions from this source http://www.gabrielgambetta.com/entity-interpolation.html. In the article it says that:

several clients may be sending inputs simultaneously, and at a fast pace (as fast as the player can issue commands, be it pressing arrow keys, moving the mouse or clicking the screen). Updating the game world every time inputs are received from each client and then broadcasting the game state would consume too much CPU and bandwidth.
A better approach is to queue the client inputs as they are received, without any processing. Instead, the game world is updated periodically at low frequency, for example 10 times per second. The delay between every update, 100ms in this case, is called thetime step. In every update loop iteration, all the unprocessed client input is applied (possibly in smaller time increments than the time step, to make physics more predictable), and the new game state is broadcast to the clients.

now I am wondering how to implement such a queue system? I can have an in memory queue where each input is added. and after say 100ms how many number of inputs do I process? i.e when should I stop popping events from queue and apply simulation?
from my point of view clients are sending inputs constantly which are being added to the input queue. below is the psuedocode.
queue inputQueue;

gameloop() {
   while (inputQueue not empty) { //<------obviously i cannot use this condition, what should i use then?
      inputEvent = inputQueue.front()
      updateState(inputEvent)
   }
}


texts: How do I change from positive degrees to negative degrees?

texts:
Recently, in Unity, I tried to move a sphere along a figure-eight path. It first moves in a circle, and after completing the circle, it starts the  second circle in reverse, using negative rotation. However, my plan did not work as I expected. The reason is that Unity changes negative degrees into positive degrees, so -15 degrees becomes 345 degree. Therefore, the direction of the circular movement won't change, when you flip from a positive degree to a negative degree. In other words, if the first path is clock-wise the second path (after changing the sign of the degree) will be clock-wise, too.

Is there any practical way to overcome this problem, and change the direction of rotation by changing from positive degrees to negative degrees?

Here is one of the scripts I have tried:

public class PlayerMover : MonoBehaviour
{
    float x;
    public float speed=100.1f;
    private Transform playerTransform = null;

    void Start ()
    {
        playerTransform = GetComponent<Transform>();
    }

    void Update ()
    {
        x=speed*Time.deltaTime;
        playerTransform.Rotate(0, 5 *funct(x) * x, 0);
        playerTransform.position += playerTransform.forward ;
    }

    public float funct(float u)
    {
        u=Mathf.Sin(u);
        return u;
    }
}

As you can see. even the function I use to flip from positive degrees to negative degrees is a smooth and continuous function, mathematically speaking.


texts:
I am making a dungeon map generator and am currently trying to make it place empty rooms. It first checks if the space is empty and then places a room.
The problem is that most of the times it compiles and I get a map/2d array printed, but sometimes it compiles but doesn't print the map. I don't get an error.

public class Mapa {

public static void main(String[] args) {
     // Create a 2D array map filled with floors

    char map1[][] = new char[100][100];
    for (int i = 0; i < map1.length; i++) {
        for (int j = 0; j < map1[i].length; j++) {
            map1[i][j] = tiles.wall();

        }
    }
    char mapFinal[][] = roomPlacement(map1);
    for (int i = 0; i < mapFinal.length; i++) {
        for (int j = 0; j < mapFinal[i].length; j++) {
            System.out.print(mapFinal[i][j] + " ");
        }
        System.out.println();
    }

}

public static char[][] roomPlacement(char map1[][]) {
     // this method places rooms into the 2D array map

    char mapReplacement[][] = map1;

    int roomNumber = (int) (10 + (Math.random() * 10));
    int roomLength = (int) (10 + (Math.random() * 10));
    int roomWidth = (int) (10 + (Math.random() * 10));

    int startPositionX = (int) (Math.random() * (mapReplacement.length - roomLength));
    int startPositionY = (int) (Math.random() * (mapReplacement.length - roomWidth));

    int counter = 0;

    while (roomNumber > counter  ) {
        if (position(startPositionX, startPositionY, roomLength, roomWidth, mapReplacement)) {

            if (roomSpace(mapReplacement, startPositionX, startPositionY, roomLength, roomWidth) == true) {
                for (int i = startPositionX; i < (startPositionX + roomLength); i++) {
                    for (int j = startPositionY; j < (startPositionY + roomWidth); j++) {
                        mapReplacement[i][j] = tiles.floor();
                    }
                }
            }
            if (roomSpace(mapReplacement, startPositionX, startPositionY, roomLength, roomWidth) == false) {
                startPositionX = (int) (Math.random() * (mapReplacement.length - roomLength));
                startPositionY = (int) (Math.random() * (mapReplacement.length - roomWidth));

            }

            counter++;
        }

        roomLength = (int) (10 + (Math.random() * 10));
        roomWidth = (int) (10 + (Math.random() * 10));

    }

    return mapReplacement;
}

public static boolean roomSpace(char map1[][], int startPositionX, int startPositionY, int roomLength,
        int roomWidth) {
    // this method checks if there is enough free space

    boolean isFreeSpace = false;
    char mapCheck[][] = map1;

    int counter = 0;
    for (int i = startPositionX; i < (startPositionX + roomLength); i++) {
        for (int j = startPositionY; j < (startPositionY + roomWidth); j++) {
            if (mapCheck[i][j] == tiles.wall()) {
                counter++;
            }
        }
    }

    if (counter == (roomLength * roomWidth)) {
        isFreeSpace = true;
    }

    if (isFreeSpace == true) {
        System.out.println("true");
    } else if (isFreeSpace == false) {
        System.out.println("false");
    }

    return isFreeSpace;

}

public static boolean position(int startPositionX, int startPositionY, int roomLength, int roomWidth,
        char mapReplacement[][]) {
    boolean position = false;
    // checks if the room is out of bounds
    if (startPositionX > 0 && startPositionX < mapReplacement.length && startPositionX + roomLength > 0
            && startPositionX + roomLength < mapReplacement.length && startPositionY > 0
            && startPositionY < mapReplacement.length && startPositionY + roomWidth > 0
            && startPositionY + roomWidth < mapReplacement.length) {
        position = true;
    }

    return position;
}

  }

Sorry for the long code but wanted to let you see the whole code to better understand it


texts:
I am texturing a tree in bender using the sappling add-on, when i put the tree bark texture (which is saved as .jpg) the texture looks stretched and wierd, ive used "Use UV for mapping" on the curve modifier and it still looks stretched. I have blender 2.75.

Thanks in advance.  :)


texts: What is "procedural generation" and how is it done?

texts: I hear a lot about "procedural maps" and "procedural textures". What does that mean exactly, and what resources are there for learning these techniques in a game?


texts:
I finished my game and it runs fine inside Unity. I exported it to WebGL and ran it there but the main menu background does not show. It looks the background color and is pretty annoying. Here are some snapshots:

It's supposed to look like this. It looks like this when I run in Unity.
But when I export the game, here is what I see:

Anyone know where should I look to fix this? Here are my player settings:


texts: Creating materials in modeling program vs in Unity: when to do either?

texts:
This is something I should know the answer to by now, so I'm asking to clear up the gaps in my knowledge:

As I (re)learn about shaders, specifically in relation to Unity, I see all sorts of ways to create shaders/materials from within Unity to achieve various visual effects. (using Shader Forge / Shader Graph / manually writing ShaderLab or other shader languages).

I'm also aware that you can create shaders/materials from 3D modeling programs such as 3DS Max.  My questions are: When would you choose one method over the other, or could you use both in conjunction?  What is a normal workflow?  Does material creation in Unity offer context-specific features that are not supported by modeling programs?


texts: How to calculate distance of travel needed get achieve speed x?

texts:
I have a boat traveling at 20 meters/second approaching destination x. Destination x has a range radius of 10 meters. What I would like to do is make sure by the time the boat arrives within 10 meters of destination x (i.e. boat gets to touch the orange circle) the boat speed is brought down to 5 m/s. The boat can decelerate at a rate of 0.5 m/s^2.

My solution:

I believe I need to first calculate the distance required to slow down to 5 m/s.

using the following equation of motion:

v^2 = u^2 + 2as

where:

v: final velocity
u: initial velocity
a: acceleration; -acceleration = deceleration
s: displacement or distance

we can rearrange the variables in the formula above like so:

s=(u^2-v^2)/(-2a)

applying the following given variables:

v = 5
u = 20
a = -0.5

we have:

s=(20^2-5^2)/(-2(-0.5)) = (400-25)/1 = 375

this means that at any moment of travel we need a distance of 375 meters to slow down from 20 m/s to 5 m/s. Now adding the fact that we need to slow down before we reach the circumference of the orange circle, we need to make sure we are at least 375 meters away.

Since we know location x, then we calculate distance from boat to (x + 10 meters), call it d.

We check if  375 <= d then we start to decelerate the boat?
Is the distance required to achieve speed 5 m/s while decelerating from 20 m/s is 375 meters?
Is my approach correct? Are my calculations correct?


texts: Why don't variables in a script on a prefab clone store runtime changes?

texts:
I have a building prefab. There is a simple script attached to it that allows me to store unique data for each prefab instance, such as address. There are hundreds of clones of this prefab.

The prefab is instantiated like so:

//instantiate a "building" object :
    multiFamHigh = Instantiate(multifamilyHigh,myV3,Quaternion.identity) as GameObject;

//set a reference to the prefab's behavior script:
    BuildingBehavior bldgBhave = multiFamHigh.GetComponent<BuildingBehavior>();

//set the information for the prefab:
    bldgBhave.setInfo( mgr.lotsList[chose].getAddress(),buildingRef);

In the "TownCreator" script, after the prefab is instantiated, I call the setInfo function and pass the address to it. The setInfo looks like this:

public class BuildingBehavior : MonoBehaviour {

    private string address;

public void setInfo(string useString, int bldgListRef)
    {
        address = useString;
        Debug.Log ("Set Address = " + address);
        buildingListRef = bldgListRef;
    }
}

The debug log correctly displays "you set address 3071 N." - meaning at that time, the "address" variable of the prefab script is set to 3071 N. Perfect.

However; later, when I click on any of the prefabs at runtime (via the mousedown) the UI message box pops up (as intended), and the Text is changed from "New Text" (default) to a blank string. I added a similar Debug.Log, at that point, and it also tells me that "address" on the clone is blank.

That code is:

 void OnMouseDown()
    {
        thisCG = GameObject.Find("MainCanvas").GetComponent<CanvasGroup>();
        thisCG.alpha = 1;
        CanvasStuff thisCS = GameObject.Find("MainCanvas").GetComponent<CanvasStuff>();
        thisCS.setAddyText (address);
        Debug.Log ("clicked on " + address);
    }

This happens:

Any ideas why the script on the prefab clones is not storing the values?

Also - when I change (address) to ("Address"), the popup has "Address" above the OK, Thanks! button. :/


texts: Must all AI states be able to react to any event?

texts:
FSMs implemented with the State design pattern are a common way to design AI agents. I am familiar with the State design pattern and know how to implement it.

How is this used in games to design AI agents?

Consider a simplified class Monster, representing an AI agent:

class Monster {
    State state;
    // other fields omitted

    public void update(){ // called every game-loop cycle
        state.execute(this);
    }

    public void setState(State state){
        this.state = state;
    }

    // irrelevant stuff omitted
}

There are several State subclasses implementing execute() differently. So far, classic State pattern.

AI agents are subject to environmental effects and other objects communicating with them. For example, an AI agent might tell another AI agent to attack (i.e. agent.attack()). Or a fireball might tell an AI agent to fall down. This means that the agent must have methods such as attack() and fallDown(), or commonly some message receiving mechanism to understand such messages.

With an FSM, the current State of the agent should be the one taking care of such method calls - i.e. the agent delegates to the current state upon every event. Is this correct?
If correct, how is this done? Are all states obligated by their superclass to implement methods such as attack(), fallDown() etc., so the agent can always delegate to them on almost every event? Or is it done in some other way?


texts: Is it possible to a create an Android game that uses the built in keyboard?

texts: I know the keyboard is probably built into the Android OS and I have a simple game idea, sort of like a word game, but is it possible to create a game that uses this in the game itself?


texts: Cylinder scrolling / wrap-around world using shaders?

texts:
I am making a 2D game using OpenGL ES 2.0 (libgdx), where the world will wrap-around itself on Y-axis.

Apart from implementing the "modulo" method in my rendering code, I'm wondering whether it's possible to render such a world using only shaders?

How would I go about handling the edge case in GLSL?

EDIT: Basically, I want to move this part of the code to the GPU, if possible.


texts: What strategies can I use to update the visuals of my game to be more modern?

texts:
I'm  making a browser strategy game.

Now my problem is that I have a feeling that my design is dated.
For now I have only used background colors and borders to make things look nice, but I have planed to add some pictures later.

Here is what it looks like now:

(Click for larger)

You will see that the game has a top and bottom bar and has the main section in the middle.  My main concern is that this may not be best idea, because not full width and height of the window is used.

What strategies can I use to update the visuals of the site to a more modern look?


texts: OpenGL Shadow Mapping from directional light

texts:
I have read this tutorial:
http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-16-shadow-mapping/

I wonder, is this the current best technique for generating shadows in an arbitrary 3D scene? Is it the way current modern games implements directional light shadows or are they using some other better way of calculating shadows on the fly?

What I mean is if you know your geometry so good that you know exactly every impact a shadow can have on an objects colors, it must be better to use that information instead of rendering a Shadow map?

For example, if we have a 3D grid world with all perfect cubes at perfect offset (think minecraft) and the directional light if exactly 45 degree in all dimensions, that leave us with a situation where a cube closer to the light will also cast shadow on the entire cubes at position offset -1, -1, -1 from that cube, and so on. The shadows always go diagonal and put other equally sized cubes sides in 1 of three states: all shadow, all light or 50% in shadow.

If we know our geometry so good, then using that information must be much faster than rendering shadow maps right? Even when most of such calculation is done on the CPU instead of the GPU.


texts: How do I find a unit vector of another in Java?

texts:
I'm writing a Java formula based on this tutorial: 2-D elastic collisions without Trigonometry. I am in the section "Elastic Collisions in 2 Dimensions". Part of step 1 says:

  Next, find the unit vector of n, which we will call un. This is done by dividing by the magnitude of n.

My below code represents the normal vector of 2 objects (I'm using a simple array to represent the normal vector).

int[] normal = new int[2];
normal[0] = ball2.x - ball1.x;
normal[1] = ball2.y - ball1.y;

I am unsure what the tutorial means by dividing the magnitude of n to get the un.

What is un? How can I calculate it with my Java array?


texts: Frame independent buoyancy using Substepping

texts:
I am having trouble with a frame independent buoyancy force using substepping in Unreal Engine 4.

The original problem (which I am attempting to solve using substepping) is that when you apply a buoyancy force (which is proportional to the depth of the object), the force needs to change as the object rises out of the water. Consider the following, where an object is under water and we either have 2FPS or 42FPS (the curve representing the true force of the object as is rises)

Clearly the lower the framerate, the larger force is applied for too long resulting in the object accelerating too much.

Substepping alone does not fix this as the force being applied isn't recalculated every substep.

If I hook the force calculation into the substep then compare running at 60FPS and 10FPS I  can see that at 10FPS I get 6 substeps every frame so I believe it should be the same.

However, I still see a discrepancy. That is, at 10 FPS the object leaves the water at almost double the velocity.

Some data from the 60 vs. 10 FPS runs

                       |  60FPS      |   10FPS
___________________________________________________
Velocity Leaving Water |  815 cm/s   |   1576cm/s
Time in water          |  0.89s      |   0.43s
Total displacement     |  122        |   41.84
Max Displacement       |  209cm      |   150cm

Here the time in water is measured by summing the dt's of each substep and the total displacement is the displacement at each substep multiplied by the dt.

I believe the problem is that the elapsed physics time is nearly double for the higher frame rate, though why this would mean the lower frame rate one comes out faster, I don't understand.

The code to apply the force is:

void UBuoyantPointComponent::CalculateBuoyancyPhysics(float DeltaTime, FBodyInstance* BI)
{
    // Data passed in from the main thread, now just reduced to the components offset which doesn't change
    PhysicsLock.lock();
    FPhysSubstepData LocalSubstepData = FPhysSubstepData(SubstepData);
    PhysicsLock.unlock();

    FTransform BodyTransform = BI->GetUnrealWorldTransform();
    const FVector& CalcCompLocation = (LocalSubstepData.ComponentOffset * BodyTransform).GetLocation();

    const float Altitude = CalcCompLocation.Z;
    const float Difference = 0.0f - Altitude;

    if (Difference > 0) // we are under the sea since the wave height is greater than the height of this point
    {
        float SubmergedVolume = FMath::Min(Difference, 100.0f) * 100.0f * 100.0f;

        FVector ComputedForce = ((FVector::UpVector * SubmergedVolume * BuoyancyStrength));
        BI->AddForceAtPosition(ComputedForce, CalcCompLocation);
    }
}

I can't even work out what I can try to gain more insight into this so any help would be greatly appreciated.

Update

Printing out data every substep reveals some interesting things that I didn't spot before. (Full log, the --- indicates a game tick, each line is a substep tick). In summary though:

The first set of substeps don't actually move the object at all

This means after the first frame the 10FPS object is moving considerably faster than the 60FPS one since it has had a longer period of not moving and just accumulating force.

dv calculation seems to be out by a half

My dv which I think should be how much the velocity changes from to frame seems to be out by a factor of a half. It is being computed in the following way:

`DeltaTime * ((SubmergedVolume * BuoyancyStrength) / BI->GetBodyMass())`

Where (SubmergedVolume * BuoyancyStrength) is the only force applied to the object.

This discrepancy is magnified by the lower framerate and the objects speed increases twice a fast at lower depths (i.e. larger force) for longer.


texts:
I'm working on a game where the player can pick up objects using something like a tractor beam, and carry them around.

Attracting the object towards the center of the beam is not difficult. But once the object is close enough to the center, I need to keep it there while the player moves, which is what I'm having problems with. I can think of two ways to do it, and both have issues:

Update the object's position whenever the player position changes, keeping it centered on the beam.
Update the object's velocity to point directly towards the center of the beam, the further away, the more velocity.

Moving and rotating works just fine with both approaches, but the physics are wrong when the carried object collides with other objects:

With the first approach, physics are completely ignored. The carried object just pushes anything out of the way. That is because position changes are only supposed to be done as part of the world physics, based on velocity.

With the second approach, physics basically behave how they should, but overreact. The problem is: In order to keep the carried object at the center of the beam even when rotating and moving, I need to use high velocity values. So once the carried object touches another one, it gets way too much velocity from the collision.

How can I implement this properly? My best guess right now is to go with the second approach and add special handling for carried objects to the world physics, reducing the velocity to sane values for collisions or when the player stops carrying them. But that seems like a pretty inelegant workaround.

Edit: Adding some pseudo code to illustrate how it works right now (that'd be the second approach above)

void attract_object(object, ticks) {
    Vector distance = beam_center - object.center;
    // If the object is not close to the beam center, attract it slowly
    if (magnitude(distance) > 10) {
        object.velocity += distance.normalized() * ticks * 0.1;
        return;
    }

    // Here comes the part we're talking about. That magic 0.5 is just high enough
    // that the object isn't lost while moving around. But it's still so high that
    // other objects are repelled with way too much force.
    object.velocity = distance * ticks * 0.5;
}

From what I see, this happens when the carried object pushes another object away:

The carried object collides with another object
The objects' velocities are distributes properly, so the carried object is pushed away from the center of the beam in the process
The code above causes the carried object to return to the center of the beam, with so much velocity that it'll get back there quickly
When the carried object moves back towards the center of the beam, half of its high velocity is transferred to the other object, repelling it violently. Since the initial velocity of the carried object appears to be sane, I can imagine that steps 2 to 4 are repeated multiple times, building up such a high velocity.

That appears to be the cause. I can't think of a nice way to fix it though :(


texts: How to get an AbstractClientPlayer for all players?

texts:
I'm working on an minecraft forge mod (1.8.8). I have en custom (ownable) entity and want to set its texture to the texture of its owner, because it's a mini version of the owner.

I found out that i can get the texture of players with AbstractClientPlayer#getLocationSkin(), but i can't figure out how to access either EntityOtherPlayerMP or EntityPlayerSP, which implement AbstractClientPlayer, in my custom renderer. Is there a way to get all AbstractClientPlayer, regardless of SP or MP? I can access the GameProfile and i have the EntityPlayer of the owner.


texts:
I am using unity's scrollview.
I want to disable the vertical scrollbar and i want the viewport to resize vertically depending on the content.
Too confusing to explain with word so i have created the example picture below :

How do i achieve this properly ?


texts: How can I describe a square in OpenGL ES 2.0?

texts: I need to draw a Tic-Tac-Toe board in Xcode using OpenGL ES 2.0. I am new to graphics programming and can't find good information on drawing a square in opengl es in iOS. I looked at Ray's tutorials, which are good, however he covers drawing a rotating cube. All I want is a square; how can I describe a square for OpenGL?


texts:
Let's assume that I can pick a fairly decent game, build it, and finish it with sufficient chrome plating; let's also assume that I can market it myself to some extent, through my own website.

What exactly are the advantages of going through Steam Greenlight? Assuming I can actually get through the process and reach sufficient critical mass to be "Greenlight." Do you know what usually becomes of finished, polished, chrome-plated games that get "greenlit?" Statistically, does greenlighting correlate with commercial success or higher sales?

By the way, I'm assuming my marketing sucks, and that Steam, in general, gets some eyeballs and sales for you.


texts:
I am having trouble with my 2-D wall-sliding.  Namely, when the player avatar collides with the wall, it "snaps" to the corner (see screenshot, below) and sticks there.  The red, transparent rectangle is my "wall":

My code is as follows:

"FootRectangle" is your standard xna rectangle. Location is a vector2.  The player is moving to a target, which could be anywhere on the screen, which is also a vector2.

 if (wall.CollisionRectangle.Intersects(player.FootRectangle))
            {

                // collision above block
                if (player.FootRectangle.Top <= wall.CollisionRectangle.Top)
                {
                    player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Top - player.FootRectangle.Height / 2);
                }

                // collision below block
                else if (player.FootRectangle.Bottom >= wall.CollisionRectangle.Bottom)
                {
                    //player.FootRectangle.Y = block.CollisionRectangle.Bottom;
                    player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Bottom + player.FootRectangle.Height / 2);
                }

                // collision left of block
                if (player.FootRectangle.Left <= wall.CollisionRectangle.Left)
                {
                    player.Location = new Vector2(wall.CollisionRectangle.Left - player.FootRectangle.Width / 2, player.Location.Y);
                }

                // collision right of block
                else if (player.FootRectangle.Right >= wall.CollisionRectangle.Right)
                {
                    player.Location = new Vector2(wall.CollisionRectangle.Right + player.FootRectangle.Width / 2, player.Location.Y);
                }

How can I resolve these collisions so that the avatar snaps to a corner and smoothly makes his way to the target destnation?

I attempted to implement a similar solution to that at this post; however, it seemed to stick when the collision occurred.


texts:
Cossacks (released in 2002) is an RTS game where you can build huge (few thousands men per player) armies on a really big maps. Imagine Age of Empires 2 for few players on Ludikris map with no lag, with 8000 units on the map (or even bigger map with even more units!).
What is interesting is the fact, that if you send this huge army to the other corner of the map ... the game does not stall. Units just start moving towards their target position. There are obstacles on the way, like hills, buildings, walls etc, which are avoided by units.

There is, however, a problem with pathfinding - sometimes units just go back and forth around hills, so that might indicate, that whole path length is divided into smaller parts and units' gets confused. But still, that's massive amount of computation to be done for a few-thousand-men army, really impressive.

Do you have any idea how such smooth (in terms of performance) pathfinding was/could be achieved?


texts:
So I want to develop a Dota2-like armor system where damage reduction never reaches 100%.

Armor values be like:

Armor --- Reduction

10 ---------- 10%

20 ---------- 19%

30 ---------- 27%

40 ---------- 35%

How to make something like that, where reduction never reachs 100%?


texts:
I am currently hard coding 10 different instances like the code below, but but I'd like to create many more. Instead of having the same layout for the new level, I was wondering if there is anyway to generate a random X value for each block (this will be how far into the level it is). A level 100,000 pixels wide would be good enough but if anyone knows a system to make the level go on and on, I'd like to know that too. This is basically how I define a block now (with irrelevant code removed):

block = new Block(R.drawable.block, 400, platformheight);
block2 = new Block(R.drawable.block, 600, platformheight);
block3 = new Block(R.drawable.block, 750, platformheight);

The 400 is the X position, which I'd like to place randomly through the level, the platformheight variable defines the Y position which I don't want to change.


texts: How to use touch screen for movement instead of keyboard narrow keys

texts:
I wrote this code and run the game on my desktop, now I need to build this game for android and I need to change to touch to move the player, what it should be changed in the following code and what is the necessary steps to build my desktop 2D game to be run on android device, the following is the player code:

#pragma strict

var speed : int = 5;

function Start () {
}

function Update () {

  if(Input.GetAxis("Horizontal") >0){

    if(collided_with != null) {
      if(collided_with.tag== "Right") {
        //collided_with=null;
        return;
      }
    }
    transform.Translate(Vector3(Input.GetAxis("Horizontal")*speed*Time.deltaTime,0,0));
  }

  if(Input.GetAxis("Horizontal") <0) {
    if(collided_with != null) {
      if(collided_with.tag == "Left"){
        // collided_with=null;
        return;
      }
    }
    transform.Translate(Vector3(Input.GetAxis("Horizontal")*speed*Time.deltaTime,0,0));
  }
}


texts:
I'm trying to display a game in the console window using a screen buffer but cannot compile it.

I have this simple code:

#include <Windows.h>
#include <iostream>
#include <thread>

int main() {
  const int width = 120, height = 40;

  wchar_t* screen = new wchar_t[width * height];
  HANDLE console = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
  SetConsoleActiveScreenBuffer(console);
  DWORD bytesWritten = 0;

  while (true) {
    for (int i = 0; i < width * height; i++) screen[i] = L' ';
    wsprintf(&screen[width + 5], L"Testing");

    WriteConsoleOutputCharacter(console, screen, width * height, {0, 0}, &bytesWritten);
    Sleep(1000 / 30);
  }

  return 0;
}

It won't compile, getting two errors:

  test.cpp:16:44: error: cannot convert 'wchar_t*' to 'LPSTR {aka char*}' for argument '1' to 'int wsprintfA(LPSTR, LPCSTR, ...)'

and

  test.cpp:18:87: error: cannot convert 'wchar_t*' to 'LPCSTR {aka const char*}' for argument '2' to 'BOOL WriteConsoleOutputCharacterA(HANDLE, LPCSTR, DWORD, COORD, PDWORD)'

How can I get this working and how to do it even better?

I'm using g++ 6.3.0 to compile.

Thanks!


texts:
I have a problem regarding how the values under a certain parameter doesn't change after being called again.

I have this kind of code, where, an imp (monster) and a character has to go for a battle:

#include <iostream>
using namespace std;

int gems = 0;

float imp (float imphp) {
float implife = imphp - 5.0;
return implife;
};

float character (float charlife) {
float charalives = charlife - 2.0;
return charalives;
};

int main () {
string charactername;
cout << "Hero Life: ";
cout << character(10.0) <<endl;
cout << "Monster Life: ";
cout << imp (10.0) <<endl;

};

My problem or rather a question is if I call the monster function again is that it returns the value as 1.

Code I used to call monster for the second time after the first turns of damage is done:

cout << monster << endl;

what happens there was it sends me a value of 1. how can i make it show the current value after the damage has been taken...? say if the imp takes another damage, how can i make my program show the current value, since if the imp took out 2.0 at first attack, then takes another 2.0, the value for the hp of the character to show is 6.0? Same with the other function, how can i return it to the current value?


texts: how to modify shadow mapping in "3D Graphics with XNA Game Studio 4.0"?

texts:
So I've been following the tutorials from the book Sean James's "3D Graphics with XNA Game Studio 4.0", and have been doing fine until i reached the shadow mapping part.
in this book it creates point lights with a Sphere model.
my first Q is how to draw a directional Light with this frame work?
secondly it can do shadow mapping just for one light,
how can i do shadow mapping for all or parts of the lights in the game?
i just want to know how to modify this codes to do the above tasks.
I've followed tutorials on MSDN and some other sites and didn't got the answer.
please help me, its so urgent.


texts: Import JXInput by StrikerX3 Into Eclipse

texts:
I'll be honest, I'm stumped, I've been trying all night, googling away, made multiple attempts and failed every time. The library in question that I'm trying to add to my project is:
https://github.com/StrikerX3/JXInput
The instructions say:

Usage:
1. Install the project into your Maven repository (since it is not available in the Central Maven repository).

2. Include the Maven dependency into your project:

<dependency>
    <groupId>com.ivan</groupId>
    <artifactId>xinput-device</artifactId>
    <version>0.5</version>
</dependency>

3. There is no need to extract or copy the native libraries from the VS project. The natives are included in the jar file and are extracted and loaded at runtime automatically under the lib folder of the working directory.

4. In your Java code, import the com.ivan.xinput.XInputDevice class for XInput 1.3 functionality or com.ivan.xinput.XInputDevice14 for XInput 1.4. The latter class extends the former so you can use 1.3 methods with the 1.4 class.

5. To check if the desired version is available:

// check if XInput 1.3 is available
if (XInputDevice.isAvailable()) {
    System.out.println("XInput 1.3 is available on this platform.");
}

// check if XInput 1.4 is available
if (XInputDevice14.isAvailable()) {
    System.out.println("XInput 1.4 is available on this platform.");

I'm using the current latest version of Eclipse and have the latest version of Java installed. I have a simple project I'm working on, just a JOGL based 3D application.
The first step says, "1. Install the project into your Maven repository". This is where I'm most confused.. I've never used Maven before, I don't know how to use it. After some googling, I unzipped the project into my Eclipse workspace and tried going to File > Import > Maven > Existing Maven Projects and imported the project.
Next the instructions refer to Maven dependency. I tried setting the dependency on the maven project, but I'm not sure if I was even in the right place for that.
The 3rd instruction refers to natives included in a Jar file, but after much searching I can't find a Jar file inside of any of the files provided by the library.
After that I tried to follow the rest of the instructions but obviously nothing has worked. I've fiddled with many settings and tried what I can all night to make this work but I can't see what it is I'm meant to do.
Can anyone give me any hints? Has anyone done this before who can give me a quick howto on this? I just don't know what I'm meant to do, any help would be greatly appreciated.


texts: Score won't save to Android in Game Maker Studio 1.4

texts:
I have oController as the first object to run when the game is opened. In oController's Game Start event
I have the following code:
ini_open(working_directory + "SavedScores.ini");
var highscores = ini_read_real("Highscores", "Score", 0);
ini_close();

global.LastScore = highscores;

When the player has gotten their score, I use this code to save it:
if global.gameOver {

    if global.LastScore == 0 {
        global.LastScore = global.currentScore;

        ini_open(working_directory + "SavedScores.ini");
        ini_write_real("Highscores", "Score", global.LastScore);
        ini_close();
    } else {
        if global.currentScore > global.LastScore {
            global.LastScore = global.currentScore;

            ini_open(working_directory + "SavedScores.ini");
            ini_write_real("Highscores", "Score", global.LastScore);
            ini_close();
        }
    }
}

Whenever I relaunch the game on my phone, it won't load the score I got when I previously launched the game. Idk why it's not saving?


texts: How to know if these profiler values are good or bad?

texts:
I'm making a 2D game for Android Mobile using LibGDX and Java in Android Studio. My game mostly runs alright with 60FPS, but for some time to time it lowers to 50FPS. I'm trying to find out what causes it. I came across this profiler and implemented it and here are the values in a very "messy" frame with lots of objects going around and messing around:

06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Calls: 498
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Draw Calls: 37
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Shader Switches: 8
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Bindings: 36
06-19 15:14:21.088 9999-10033/com.gadarts.parashoot.android I/GL Report - Vertex Count: 31.945946

My question is how am I supposed to know if these are considered to be high values or low? I read the LibGDX documentation but it doesn't give any direction or indication about the values effect. Yes, it might be an opinion-based question, but at least someone can give relevant direction using these values?

Thanks in advance


texts: Can an application break the graphics card?

texts:
Quick note: I know this is a game development Q&A site but I guess you guys most of all know and have experience with graphics cards so I address this question to you. If you think this is completely off-topic, please refer me to a proper site/forum. Edit: Actually, it is gamedev-related: if a bad code can result in card overheating or breaking then game developers should be aware of that and make sure their applications don't do that.

This might seem like a weird or stupid question but is it actually possible to write such a graphics rendering application that can break the graphics card (in any way)?

The immediate reason that made me ask this question was (no surprise) my own broken graphics card. After having it repaired the serviceman said that they tested various apps (games) on it and it worked fine. But when I launched my own app (deferred shading demo) it heated it to over 100 degrees Celsius. So my card didn't turn out to be fixed after all but what's important here is that the problem seemed to only occur when running my own app.

I've played various GPU-demanding games on it (like Crysis) and often pushed it to the limit and more (had settings so high that the games ran at 5 FPS), some benchmarks as well... So I've given my card, many times, so much work-load that it couldn't catch up (hence low FPS) but it never reached dangerous temperatures. But my own application managed to achieve that (at least when the v-sync was off). :P Since it was only my own app, I don't think a bad cooling system was the culprit.

So I ask - do you think (or maybe know) whether or not it is possible to break the graphics card (in any way, not just by overheating) by some vicious code?

Update:

Joe Swindell said that overheating may be the problem (well, it definitely can break the card). But shouldn't a proper cooling system prevent that from happening (under any circumstances)?

Boreal pointed out another problem. If I understand correctly, FPS is bound by both CPU and GPU (is that right?). So low FPS might signal either high CPU load or high GPU load. But again - shouldn't a proper cooling system prevent GPU from overheating even if the card is "used at 100% all the time"?


texts: Why do my sprites have a dark shadow/line/frame surrounding the texture?

texts:
I'm starting OpenGL with Apple's GLKit hand I'm having some trouble to get my sprites displayed properly. The Problem is that they all are surrounded with thin dark lines. The screen shot below shows two rectangles with a png image textures containing transparency (obviously).

The black shadows, surrounding them are definitely not part of the pngS. The green png is done without anti-aliasing the blue one has an anti-aliased border. The black border is also apparent if I draw only one sprite.

Te relevant part (hope so...) of code is:

//render the scene
-(void)render
{
    glClearColor(69./255., 115./255., 213./255., 1.);
    glClear(GL_COLOR_BUFFER_BIT);
    [shapes enumerateObjectsUsingBlock:^(AAAShape *shape, NSUInteger idx, BOOL *stop)
     {
         [shape renderInScene:self];
     }];
}

//creating and storing the effect inside shape class
-(GLKBaseEffect *)effect
{
    if(!effect)
    {
        effect = [[GLKBaseEffect alloc] init];
    }
    return effect;
}

//rendering the shape (including effect configuration)
-(void)renderInScene:(AAAScene *)scene
{
    //TODO: Storing vertices in Buffer
    self.effect.transform.projectionMatrix = scene.projectionMatrix;
    self.effect.transform.modelviewMatrix = self.objectMatrix;
    if(texture)
    {
        self.effect.texture2d0.enabled = GL_TRUE;
        self.effect.texture2d0.envMode = GLKTextureEnvModeReplace;
        self.effect.texture2d0.target = GLKTextureTarget2D;
        self.effect.texture2d0.name = texture.name;
    }
    [self.effect prepareToDraw];

    if(texture)
    {
        glEnableVertexAttribArray(GLKVertexAttribTexCoord0);
        glVertexAttribPointer(GLKVertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, 0, self.textureCoordinates);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 2, GL_FLOAT, GL_FALSE, 0, self.vertices);
    glDrawArrays(GL_TRIANGLE_FAN, 0, self.vertexCount);
    glDisableVertexAttribArray(GLKVertexAttribPosition);

    if(texture)
    {
        glDisableVertexAttribArray(GLKVertexAttribTexCoord0);
        glDisable(GL_BLEND);
    }
}

Any ideas anyone? Thank you.


texts: How should I structure my code to add enemies?

texts:
So I am currently making a 1942-style game in Sprite Kit. I've reached the point where I am finished implementing pretty much everything (movement, shooting (also recognizing a hit and exploding an object), menu,etc..) ..expect for enemies. Since I am not so experienced in programming I wasn't quite sure how I should implement my enemies.

I wanted to have different enemy "classes" in my game (in a way where they have different appearance / weapons, etc) and I also wanted the game to spawn stronger classes in the game with time. (e.g: at the beginning of the game there are green enemies with one-shot weapons; 3minutes in they should be red and fire two-shots)

How should I code my enemies? Should I do different classes (what I am currently thinking) or should I declare them with strings or do the properties with a .plist file? (on a side node: how can I access my plist properties from the scene code?)

Do you have other tips for me regarding enemies/classes/plist files?

Or..are there any other ways specifically in Sprite Kit to do this kind of stuff?


texts: Google Play Game Services Detecting Top 3 Players

texts:
I used Google Play Services Leaderboard in my Libgdx game. This is what I want to do; I would like to give awards to the best 3 players in this table. How can I help you?
It automatically connects to the Google Play Services Leaderboard and I can show players' information in the game.
Please help


texts: How do I access device camera in GameMaker Studio 1.4?

texts: I've looked everywhere in the documentation for GameMaker and I didn't find anything about how to access the camera.


texts: Vector Art Tool: Size, Position, Shapes, Symbols

texts:
I'm looking for a vector art tool for gameart, similar to Flash, but preferably free. It just needs the following capabilities:

Create vector images (can scale up/down without losing quality)
Specify shape X/Y to the pixel (eg. set the X to 24.1, like in Flash)
Draw primitive shapes (square/circle/triangle) with border and colour (or gradient)
Specify shape width/height in precise pixels
Export to PNG

Flash can do all this, but it's expensive (and heavy to install). Is there a free alternative that I can use?

This is NOT for pixely, pixel-style art.


texts: How to find a point of taking into account the distortion of the projection

texts:
I can not find the material that will help me to implement the algorithm of coordinate transformation based on the distortion of the projection.

I am creating a code recognition algorithm (similar to qr-code). After recognizing the image I get the three points.

My problem that image have different projection distortion, size and angle.

How do I find the k point, knowing the coordinates of p1, p2, p3 with distortion and without distortion of the projections.

Help me to understand! Perhaps there are ready-made algorithms or literature that will help implement it.

It is very important for me. Thank you!


texts: How to determine if the player between two points?

texts:
I'm making a skating game and I'm having trouble figuring out how to snap the player onto grinds and rails in between multiple points. My plan was to snap the player onto a point in between the two points using lerp, check which direction the player is facing using the dot product to compare direction of the rail from its first point to second and its second point to first and move them in direction that they are closer to.

But I'm having trouble with the first step. If the rail is more than two points how do I determine which two points do I use for lerping?


texts: Use of NetworkHash128 assetId in Custom Spawn Handler

texts:
I was learning Custom spawn handler on Unity Manual. It says before spawning we need to Register Spawn handler using ClientScene.RegisterSpawnHandler(coinAssetId, SpawnCoin, UnSpawnCoin);
 I understood SpawnCoin and UnSpawnCoin is Handler function that will be invoked on clients but what is the use of coinAssetId?


texts: How do I find more details about a Vuforia error when going into play mode?

texts:
I want to make an AR app in Unity using Vuforia Engine. But when I try to enter play mode nothing appeared. Here's the error alert:

Since this error does not give me any clue about what went wrong, I'd like to know if there is a way to get more details about it so I can eventually figure out how to fix it.


texts:
I'm using this line of code to delete a file:

if(Gdx.files.local("/files/ids.json").exists()) {
   Gdx.files.local("/files/ids.json").delete();
}

The same code works for all previous levels except the last one. The file does exist, but the delete() method returns false.

Any help would be greatly appreciated as it has exhausted me. I've seen similar topics in Java but nothing has worked for me. It's really weird that the same code works in some cases.

Edit

Also, in case this provides any information, when I step through the program with the debugger, the delete() returns true.


texts: Ways to represent/store different regions in a non tiled map

texts:
I am developing a game where agent tribes fight each other for land.The map is a 2D map.Each agent has an instance of group object that represents their family.And each group object contains information about the tribe.

Now the issue is how to store and represent the area each tribe owns.I was thinking of something along the lines of having the land split into own-able tiles of land and then having an ArrayList of Dimensions representing the region (width,height) and also storing positions alongside in order to know where the region starts from..Now the way tribes gather the land owned is as follows:

If the current square that agent is on is free then take the land
If not then if the current square is occupied try to fight it off from the other agent group

Now please note that actual agent movement is not based on tiles therefore I am not sure if my idea of representing the own able land as tiles is good for this.

So I am seeking on advice from anybody who has had a similar problem to deal with or have good ideas that they can share.

Also I am attaching an image to better explain my situation.

NOTE: The rectangles of different colours represent the areas owned by the agents whereas the circles in different colours are the agents themselves.


texts: How do I calculate rotation caused by bounce friction?

texts:
Following on from my previous question: I have the ball quite realistically bouncing from surfaces it hits. Now I'd like to make it spin from the friction of the hit.

Showing this is simple enough: I rotate the ball by its angular velocity every tick and apply the same rotation when it's rendered.

When a ball hits a wall, I know that the speed of rotation is affected by...

the ball's initial speed when hitting the surface
the friction coefficients of the ball and surface (physical constants)
the angle of incidence (the angle between the ball's incoming velocity vector and the surface normal).

The angle of incidence is approximated by the dot product of the ball's impact and exit velocity vectors. (1 meaning high spin, -1 meaning no spin, and everything else relatively in between)

Multiplying all of the above together and making sure they were then transformed to the range 0 - 1, and multiplied by max rotation speed, the ball seemed to respond in rotation speed as expected. Except for one thing: It would always rotate clock-wise (because of positive values).

Is this a good method? Can you think of a simpler way?

If this method seems fine, what am I missing? How do I know when the ball should be rotating counter-clockwise?


texts: Hash Distance & Angle To Produce Unique Value

texts:
I have many vertices drawn on my Unity3d C# application window (thousands). I am attempting to come up with a fast way to detect which vertex has been clicked.

My idea is to use a sorted list. The list will be ordered by a vector/vertices distance to (0,0,0):

List <KeyValuePair<double, GameObject>> vectorMap = new List <KeyValuePair<double, GameObject>>();

I use a binary search to order, search and add to the list.

Add/Insertion Method:

public void recordElementVertices(Element ele) {
    // Element is a Sub-Class of GameObject

    foreach (Vector3d v in ele.WorldVertices) {
        double distFromZero = Vector3d.Distance(Vector3d.zero, v);

        int index = -1;
        if (Algorithms.LowerBounds(vertexDistanceList, distFromZero, out index, DEF_PRECISION) != Algorithms.SearchResult.FOUND_TARGET)
            vertexDistanceList.Insert(index, new KeyValuePair<double, List<GameObject>>(distFromZero, new List<GameObject>()));

        vertexDistanceList[index].Value.Add (ele.gameObject);
    }
}

Hit Test (Search) Method:

public List<GameObject> hits(Vector3d mousePos) {

    int     index           = -1;
    double  distFromZero    = Vector3d.Distance(Vector3d.zero, mousePos);

    // Binary search will search for an exact hit or find the closest vertex to the mouse pos
    if (Algorithms.BinarySearch(vertexDistanceList, distFromZero, out index, DEF_PRECISION) == Algorithms.SearchResult.FAIL || index < 0)
        return null;

    return vertexDistanceList[index].Value; // return all game objects that occupies that vector position
}

This all works nicely and is fast but there is a major flaw. The algorithm doesn't take into account the vertices angle from (0,0,0). So 2 points that are the exact same distance from (0,0,0) but have different angles will be considered the same vertex when they are not.

For example; these 2 points lie 5 metres from (0,0,0) but have different angles. My algorithm will consider these 2 points as occupying the same place in space when they are in a completely different position.

Do you have any suggestions how I can hash a distance and angle to produce a unique result that describes that point in space? Some simple like doing Distance ^ Angle could produce a unique result but they would also produce huge numbers. A restriction is that my list sorting algorithm requires that two points close to each other should produce a hash that is similar in order to find points close to the mouse position. Hope that makes sense.

I've heard about Locatily Sensitve Hashing but it looks like implementing this algorithm would be very tricky.

Any advice would be greatly appreciated.


texts:
After researching about curves in computer graphics (splines in my case), I have come across something I did not know: Explicit functions like: \$y=x^2+2\$ are not the best way to interpolate between points because you could get 2 or more values for y for the same x. So, parametric functions seem much better for this if we make the commonly used t parameter, the distance from origin, time, etc...
After studying a bit how to convert from explicit to parametric form I have been shocked when I have found in some texts they use these parametric cubic functions to interpolate through points:
$$\begin{align}
    x(t)&=at^3 + bt^2 + ct +d \\
    y(t)&=2at^3 + 2bt^2 + 2ct +2d
\end{align}
$$
but wait... this is the exact same form the explicit function was:
$$
    y(x)= ax^3 + bx^2 + cx + d
$$
From what I have seen for other example functions in some math books the parametric funcions where not the same form that its explicit form counterpart.
Am I missing something?
Examples of the texts I'm refering to could be:
https://www.cs.helsinki.fi/group/goa/mallinnus/curves/curves.html
http://escience.anu.edu.au/lecture/cg/Spline/parametricCubicCurves.en.html


texts: Rendertarget and alphablending problem (Offscreen particle rendering)

texts:
Today, I have implemented soft particles by rendering them to a separate render target and blending that with the scene, which worked as expected with additive blended particles. In that case I render the particles to a rendertarget while blending them additively, then drawing that rendertarget in fron of the scene while blending additively, works like a charm, I even save some render time if I use a smaller render target.
In the case of alpha blended particles, I have a serious issue. First I draw them with a blend state set up for alpha blending:

D3D11_BLEND_DESC bd;
bd.RenderTarget[0].BlendEnable=true;
bd.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
bd.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
bd.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
bd.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ZERO;
bd.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
bd.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
bd.RenderTarget[0].RenderTargetWriteMask = 0x0f;
bd.IndependentBlendEnable=true;

(This is it after reading the GPU Gems article on this subject.)

The render target which I draw them to is cleared by zero for all channels. When I draw this rendertarget to the screen I use a blend state set up for alphablending (it is used for all the 2d images and definetly works well) and I get this:  It seems as if I have depth writing turned on but I made sure it is turned off.
If I draw the rendertarget with these alpha blended particles on it, but with no blending (for the RT) I get this:  Which seems correct, it just doesn't blend how I want to. On GPU gems there are sure some well described formulas for the blending, but if I set the blendstate descibed there I won't get the results they get. Could someone help me with what I am missing?


texts: SpriteBatch does not draw on graphicDevice

texts:
I'm using a control which is using XNA inside.
But when I try to draw something, it doesn't appear.
I already did a lot of tests but can't figure out what's wrong.
Here is the test I set up:

RenderTarget2D rTarget = new RenderTarget2D(GraphicsDevice, 1000, 1000);

GraphicsDevice.SetRenderTarget(rTarget);
GraphicsDevice.Clear(Color.White);
_spriteBatch.Draw(ts.Texture, layer.Location, source, Color.White, layer.Angle * (float)Math.PI /180, origin, SpriteEffects.None, 1f);
int spriteBatchGraphics = _spriteBatch.GraphicsDevice.GetHashCode();
int normalGraphics = GraphicsDevice.GetHashCode();
GraphicsDevice.SetRenderTarget(null);

using (FileStream stream = new FileStream("pic.png", FileMode.Create))
     rTarget.SaveAsPng(stream, 1000, 1000);

using (FileStream stream = new FileStream("pic2.png", FileMode.Create))
     ts.Texture.SaveAsPng(stream, ts.Texture.Width, ts.Texture.Height);

SpriteBatch.Begin, End  and GraphicDevice.Present is called too.

Because I didn't see anything, I tried to draw the stuff onto a renderTarget and save it to the HDD. I also saved the texture itself to be sure it's not just white.

However, spriteBatch should draw a 48x48 block here and I checked the parameters of spriteBatch, they are okay. But on the rendertarget, nothing appears. I reacts on GraphicDevice.Clear, the color I pick there really gets drawn.
The hashCodes of both graphicDevices are the same, so they really seem to draw to the same device.

What could cause this?

EDIT:------------------------------------------------------------------------------

I searched for some more and I found the following: I'm getting a AccessViolationException when closing the program. First I thought it's unrelated but it seems it's caused by what happened before. I found in the internet that a very bad graphic card can cause this. And the graphic card I tried this on was very bad indeed. So I tried it on an other machine now - I'm getting different results, but it's still not working and I'm still getting the exception.

Here is what it draws now:

In place of the black spot, the tile should be drawn. But it's not happening. The AccessViolationException only happens when the draw glitch happens - in this case as soon it just draws a black block instead the real texture. The lines are planed and part of it (the horizontal are still missing for some reason, but trying to fix that later).

So what is happening? Gets the graphic device too much stressed? I'm also running a game class which runs with the default loop (which manages the winforms and game).

I absolutely need the XNA technology here, because it should "preview" something from the game and using System.Drawing could change the outcome. The program also could get used by clients so a normal powered graphic card should be able to deal with it.


texts:
I am writing an app for Android, using OpenGL ES 1.x

I am confused as to whether I should use GL_FLOAT or GL_FIXED, the priority being performance regarding GPU operations(does GL_FIXED need to be converted etc. ex: GL_FIXED fits EXACTLY with the precision I need but if it is converted to a float then using it is pointless).

This book seems to say that it is ALWAYS preferable to use GL_FIXED for vertices: "The major exception is with vertex data, which should never be given in floating point..."
Here (paragraph right above the subtitle "Vertex data")

But I have seen others saying floating point is better..


texts: How area-of-effect effects are projected into games world?

texts:
I see a lot of skills in the games I play where they have a skill or a search area that projects a drawing on to a map, like a circle or something similar and I have no idea how that is done, and I don't think they use a texture to draw it. For the projection, I think, they use some kind of ray-cast to find the shape of the map and then go from there but I may be far off from truth.

In the linked image example you can see the circle is projected on the flat surface and the stairs. (And how is that glow effect around the circle achieved or is that part of a texture?)

Can someone tell me how is that done or point me to the right direction?


texts: Tips on how to architect your JavaScript game with classes

texts:
OK, so I'm creating a <canvas> game using JavaScript (ES6+) features like Classes. It's straight from the vue-cli and webpack.

So, I have these Classes with the following (and such) variables

class Player {
    this.x = 1;
    this.y = 5;
    this.name = 'Guy';
    this.stats = [];
}

class Map {
    this.level = 1;
    this.config = {};
    this.images = Image();
    this.canvas = null;
    this.context = null;
    this.board = []; // From a tileset
}

// POINT OF ENTRY STARTS HERE
// const game = new Game();
class Game {
    this.map = null;
    this.player = null;
    this.assets = Images();
}

The problem I'm having is that sometimes, I'm having to access a created object that was instantiated elsewhere.

For example, this.player was instantiated inside the Game class. But in the Map class, I have the drawMouseSelection method where it needs the current Player's X and Y and Map's board array of tiles.

For example, I pass the all of board[2500] to a static helper method in UI class to get the correct tile hovered on.

** What I am doing**

I just pass the whole object and deal with it as such. Am I passing too big of objects?


texts:
Background: We have two people in the team, one of which is a UI designer and the other is the Unity3d developer. The designer makes the 3d models in Maya and sends them to developer so that he can add interaction.

Issue: Once the developer starts putting the functionality on top of the model, we lose a lot of flexibility in terms of UI development. Specifically- any change in the textures/colours of the walls requires him to hook up the action scripts from scratch for the new model.

Question: Is there something like 'referencing' in unity3d so that we can keep improving the functionality and the aesthetics in parallel?


texts: Alternatives to Prototype pattern for Buildings

texts:
Hope some of you have ideas for this.
first I will describe the Task ahead and then go on with the my thoughts about solving it and what kind of problems I see.

1) I have a number of buildings. Their data is stored in a json file and contains stuff like name, price, maxHP, etc... all those static infos - This file can be changed or extended by additional types of buildings and my system should take them all, as long as there are no invalid data (negative health for example)

2) I need some kind of list of all buildings, that I can use to iterate over (for example to display all buildings in a build-menu)

3) I need to be able to place them somewhere and therefore create concrete instances of them in my gameworld

basically buildings can do different stuff in my game. they can create units, generate income, attack and other stuff.

my thoughts about solving it:

1) On loading my building.json, first the allowedActions of this building are looked at and the various components are added (e.g weapon component for shooting stuff) and then the actual data (like hp, damage, etc) is set and validated.

2) Currently to get a list of all my buildings and being able to place them somewhere, I do the following.
on loading buildings, I actually create an instance of each of them in order to get a List of prototypes - this prototype list is then used everywhere, where I need to be able to iterate over them, e.g. buildmenu.

3) When I then want to build it, I kind of just clone this building and update the data specific to the new clone (e.g. its actual position) and add it to my game world

So basically I'm using some kind of prototype pattern, if I understood it correct. However I don't really feel comfortable to have a list of instances of my buildings that in reality don't exist in my gameworld and for which I always have to care, that they don't ever influence the actual game (like accidently they are iterated through in a list, when I want to do something to all currently constructed buildings in my game but this will also influence the prototypes, which i clone my buildings from but are not actually constructed)

Do you have other Ideas to solve this, or is using prototypes here the right thing to do?

Thanks for any advice
Kind Regards


texts: Unity - Which is more optimal persisting between scenes? `DontDestroyOnLoad` or `LoadSceneMode.Additive`

texts:
User philip previously marked this as a duplicate question of this, but failed to actually read either question it seems. The question that this was marked as a duplicate of, does not address the Additive scene loading using Unity SceneManager.

Let me premise this with, this is not intended to be an "x vs y" opinion piece, I am simply looking for information on what is more optimal and what is the preferred way.

tldr;

I am new to unity and over the past week built a very small 2D 'Shooter' game to help me learn how to interact with the engine. When trying a new project and looking in to persisting game managers between scenes, I initially found the DontDestroyOnLoad syntax.

DontDestroyOnLoad vs LoadSceneMode

Which is more optimal for large games/scenes?
Both methods appear to do the same thing, except you create the scene yourself of additive scene loading.
New to Unity looking in to methods of persisting objects and in-memory data between scenes.
People mentioned the Unity Docs stating to not use DontDestroyOnLoad but I can't find this.

Essentially, I had the following on (at the time) two 'manager' scripts. When then calling SceneManager.LoadScene(#); in other parts of the code and in other scenes, these managers persisted between scenes.

using UnityEngine;
using UnityEngine.SceneManagement;

public class MyBehaviour : MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
}

It worked, no issues there. However when looking in to other methods to ensure what I was doing is 'good practice' and 'optimal' I had come across a few places mentioning not to use this method, a few people mentioned that the unity docs for DontDestroyOnLoad also reiterate this, I could not find such text. Instead, they mention having a 'Manager Scene' with all of the objects to persist being within that scene.

To implement this, I had to add a third manager, 'CustomSceneManager' that handles unloading the current scene and loading a new one, while persisting the current 'ManagerScene'.

using UnityEngine;
using UnityEngine.SceneManagement;

public class CustomSceneManager : MonoBehaviour
{
    private int _currentScene = -1;

    // This is in the manager scene, so the manager scene always gets pulled in to scenes
    // when a scene is switched via this method.
    public void SwitchScene(int sceneId) {
        if (_currentScene != -1) {
            SceneManager.UnloadSceneAsync(_currentScene);
        }
        _currentScene = sceneId;
        SceneManager.LoadScene(sceneId, LoadSceneMode.Additive);
    }
}

This method also works, with the overhead of a further empty GameObject / Manager to handle scene logic (I would likely need this to be a manager in the future anyway as I instance parts of the game) and the fact that anywhere I switch scene, I need to go via this manager, which means finding it/creating a reference where I want to use it vs just calling Unitys built in scene manager methods.