texts:
I'm very new to C# and Unity, and have been working on a projectile based weapon, and for the most part it's been working well. However, although the bullet fires facing the direction it's being shot horizontally, when shot up or down, the bullet is still parallel to the ground when shot. Any help would be appreciated, thanks!

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

public class PlayerWeapon : MonoBehaviour
{
public GameObject bulletPrefab;

public Transform BulletSpawn;

public float bulletSpeed = 30;

public float lifeTime = 3;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Fire();
    }
}

private void Fire()
{
    GameObject bullet = Instantiate(bulletPrefab);

    Physics.IgnoreCollision(bullet.GetComponent<Collider>(),
        BulletSpawn.parent.GetComponent<Collider>());

    bullet.transform.position = BulletSpawn.position;

    Vector3 rotation = bullet.transform.rotation.eulerAngles;

    bullet.transform.rotation = Quaternion.Euler(rotation.x, transform.eulerAngles.y, rotation.z);

    bullet.GetComponent<Rigidbody>().AddForce(BulletSpawn.forward * bulletSpeed, ForceMode.Impulse);

    StartCoroutine(DestroyBulletAfterTime(bullet, lifeTime));
    }

private IEnumerator DestroyBulletAfterTime(GameObject bullet, float delay)
{
    yield return new WaitForSeconds(delay);

    Destroy(bullet);
}
}


texts: What is an efficient packing algorithm for packing rectangles into a polygon?

texts: I need to put as many rectangle of same size as possible inside a polygon. The algorithm can put rectangles in different orientation(angle). But they cannot overlap. This is image is an example of the end result:


texts: Detect mouse click on a bezier curve's neighborhood

texts:
I'm developing a game in HTML5 and JavaScript using Canvas API for drawing graphics. I want to detect if the user has clicked on a bezier curve which has the line width of 20 pixels (something like this one on the picture). I need to validate if the user has clicked on the area drawn by the curve (red and black).

I implemented such an algorithm for lines, but could not adapt it to quadratic and cubic bezier curves. So I need an algorithm that will compare the position of a point relative to a bezier curve which has the form of

$$ B(t) = P_0 (1-t)^2 + P_1 (1-t)t + P_2t^2$$

for quadratic bezier curves or

$$ B(t) = P_0 (1-t)^3 + 3P_1 (1-t)t + 3P_2(1-t)t^2 + P_3t^3$$

for cubic bezier curves, and check if it is in the neighborhood of the bezier curve's path, I mean on the black drawn area.

[Red: Bezier curve's path; Black: Bezier curve's drawn area]


texts:
I have created a jump'n'run browser-game based on SVG. The »World« grew large (~80px * ~20000px, before scaled to viewport height) and rendering went slow. In consequence I included  a range searching algorithm to exclude elements from the render tree, if they are out of the visible area. To get all elements inside the viewport, I am using a range query on a AVL-Tree.

Basically the approach was very effective and increased the performance up to 40%, unfortunately it also results in flickering of the graphic if the player is in motion.

The initialization looks like this:

//for each element of type: path, rect, polygon, line, circle, polyline,use,text or tspan

var box = bbox.call(this, element, mtr),
  data = {
    style:    element.style,
    x1:       box[0].x,
    x2:       box[1].x,
    visible:  false
  }
this.tree.insert(box[0].x, data);
this.tree.insert(box[1].x, data);
element.style.display = 'none';

whereby bbox() creates gets the bounding box in global coordinates.

Each time at rendering the following is done:

var x1      = this.viewBox.x - 1,
    x2      = this.viewBox.x + this.viewBox.width + 1,
    result  = this.tree.query(x1, x2),
    visible = this.visible,
    i       = 0,
    n       = result.length,
    data;

for (; i < n; i++) {
  data = result[i];
  if (!data.visible) {
    data.style.display = 'block'
    data.visible = true;
  }
}

for (i = 0, n = visible.length; i < n; i++) {
  data = visible[i];
  if (data.x1 > x2 || data.x2 < x1) {
    data.style.display = 'none';
    data.visible = false;
  }
}

this.visible = result;

As mentioned above, the framerate increased between 20% and 40% on each platform, but flickering and kind of sloppy rendering began.

What could I do to gain a more fluent rendering?


texts:
I am new using Vulkan, and i am trying to learn it looking tutorials and looking the vulkan examples that they provided(vulkan-master: https://github.com/SaschaWillems/Vulkan).

One of them is the Overlaytext project. In this project they teach you how to implement an overlay text in Vulkan.

Using this code, i wanted to change it to add an additional uniform to be able to change the color of the fonts. The problem is that the uniform is not getting set to the color, is always a 0 vec4(0,0,0,0) and i am not getting any warning or error.

If you can please tell me what i am missing i will be really appreciated, i dont know anymore what to do, i am out of ideas.

The code that i added or changed of this project to add this uniform is the following:

Variables in class:

glm::vec4   _color = glm::vec4(1.0f,1.0f,1.0f,1.0f);
struct {
VkBuffer buffer;
VkDeviceMemory memory;

} _colorBuffer;

Input binding and attributes of the pipeline(preparePipeline method):

std::array<VkVertexInputBindingDescription, 3> vertexBindings = {};
vertexBindings[0] = vertexInputBindingDescription(0, sizeof(glm::vec4), VK_VERTEX_INPUT_RATE_VERTEX);
vertexBindings[1] = vertexInputBindingDescription(1, sizeof(glm::vec4), VK_VERTEX_INPUT_RATE_VERTEX);
vertexBindings[2] = vertexInputBindingDescription(2, sizeof(glm::vec4), VK_VERTEX_INPUT_RATE_VERTEX);
std::array<VkVertexInputAttributeDescription, 3> vertexAttribs = {};
// Position
vertexAttribs[0] = vertexInputAttributeDescription(0, 0, VK_FORMAT_R32G32_SFLOAT, 0);
// UV
vertexAttribs[1] = vertexInputAttributeDescription(1, 1, VK_FORMAT_R32G32_SFLOAT, sizeof(glm::vec2));
// Color
vertexAttribs[2] = vertexInputAttributeDescription(2, 2, VK_FORMAT_R32G32B32A32_SFLOAT, 0);

Added starging buffer to copy the content of the color vec4 to a local device buffer(prepareResources method):

struct {
    VkBuffer buffer;
    VkDeviceMemory memory;
} colorStaging;

ErrorCheck(renderer->CreateBuffer(
    VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
    VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
    sizeof(glm::vec4),
    &colorStaging.buffer,
    &colorStaging.memory,
    &_color));

ErrorCheck(renderer->CreateBuffer(
    VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
    VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
    sizeof(glm::vec4),
    &_colorBuffer.buffer,
    &_colorBuffer.memory));

Copy the staging buffer to the colorBuffer uniform(prepareResources, just after the setImageLayout method and before the end command buffer):

VkBufferCopy copyRegion = {};

copyRegion.size = sizeof(glm::vec4);
vkCmdCopyBuffer(
    copyCmd,
    colorStaging.buffer,
    _colorBuffer.buffer,
    1,
    &copyRegion);

Clean up staging buffer(between stagingBuffer.destroy() and vkFreeCommandBuffers(_device, _command_pool, 1, &copyCmd); in the prepareResources method):

vkDestroyBuffer(renderer->GetVulkanDevice(), colorStaging.buffer, nullptr);
vkFreeMemory(renderer->GetVulkanDevice(), colorStaging.memory, nullptr);

Added the new binding vertex to the update command buffers(update command buffers method, just next to the other bindings):

vkCmdBindVertexBuffers(_commandBuffers[i], 2, 1, &_colorBuffer.buffer, &offsets);

Vertex shader:

#version 450 core

layout (location = 0) in vec2 inPos;
layout (location = 1) in vec2 inUV;
layout (location = 2) in vec4 color;

layout (location = 0) out vec2 outUV;
layout (location = 1) out vec4 outColor;

out gl_PerVertex
{
    vec4 gl_Position;
};

void main(void)
{
    gl_Position = vec4(inPos, 0.0, 1.0);
    outUV = inUV;
    outColor = color;
}

Fragment shader:

#version 450 core

layout (location = 0) in vec2 inUV;
layout (location = 1) in vec4 inColor;

layout (binding = 0) uniform sampler2D samplerFont;

layout (location = 0) out vec4 outFragColor;

void main(void)
{
    float color = texture(samplerFont, inUV).r;

    outFragColor = inColor*color;
}

I recompiled both shaders.

If i didnt add something will mean that i didnt change it.

Thank you for attention.


texts:
In my game I have a BULLET, MOONS, STARS, and A SHIP. I shoot bullets from the ship and hit stars or moons and collisions occur. Yet when a moon runs into my ship there is no detection even though I set the a Collider for 2D on both of them.

    void OnCollisionEnter2D (Collision2D col) {
        Debug.Log (this.transform.tag);//moon hit ship not printing
        Debug.Log (col.transform.tag);//only bullet hit moons and stars
    }

Heres a quick snippet
https://i.gyazo.com/acc0bbf5d2aab994db3a6598bfd206aa.mp4


texts: Matching collider to character mesh size in different postures

texts:
What's the optimal method in Unity to match the size of a Capsule Collider to the actual size of the game object it is part of?

To understand what I'm trying to do let me give an example:

I have a 3D player character with a Capsule Collider that is used to check collision. The character can go into various postures, e.g. crouch, prone, jump. I'm having difficulties to match the height of the collider to the height of the character when crouching or jumping because depending on the used animations the character's height is smaller by various amounts when crouched or jumping.

All I could do so far is set a multiplier for a specific posture by that the collider scales but this is very inefficient, especially when the character tries to jump onto a higher ground.

There seems to be no way of knowing the exact size of a mesh. I'm not sure if it might help to loop through all child meshes (torso, hair, etc.) in a game object and obtain their bounds through SkinnedMeshRenderer.


texts: Can I release the source code of a game created with the personal edition of Unity?

texts: Does the license of Unity Personal allow the publishing of the game's source code? We want to develop a game on a hackathon and publish the code thereafter. Is this possible?


texts:
I study Computer Science at Technical University of Lodz (in Poland) with Computer Game and Simulation Technology specialization. I'm going to defend BSc thesis next year and I was wondering what topic I could choose but nothing really interesting is coming to my mind.

Maybe You could help me and suggest some subjects related to programming graphics, games or simulations? (or maybe something else that is interesting enough :) ). I would be very grateful for any suggestion!


texts: How can i use StartCoroutine to set the speed for each scaling step of the walls?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WallsTest : MonoBehaviour
{
    // using a GameObject rather than a transform
    public GameObject prefab;
    public Vector3 wallsStartPosition;
    public float width = 0;
    public float height = 1;
    public float length = 2;
    public Camera wallsCamera;

    void Start()
    {
        wallsCamera.transform.position = new Vector3(wallsStartPosition.x, wallsStartPosition.y + 100, wallsStartPosition.z - 235);

        StartCoroutine(BuildWalls());
    }

    IEnumerator BuildWalls()
    {
        for (int i = -2; i < 2; i++)
        {
            GameObject go = Instantiate(prefab);
            go.transform.parent = transform;
            Vector3 scale = Vector3.one;
            Vector3 adjustedPosition = wallsStartPosition;

            float sign = Mathf.Sign(i);
            if ((i * sign) % 2 == 0)
            {
                adjustedPosition.x += (length * sign) / 2;
                yield return new WaitForSeconds(0.1f);
                scale.x = width;
                scale.y = height;
                scale.z *= length + width;
            }
            else
            {
                adjustedPosition.z += (length * sign) / 2;
                scale.x *= length + width;
                scale.y = height;
                scale.z = width;
            }

            adjustedPosition.y += height / 2;
            go.transform.localScale = scale;
            go.transform.localPosition = adjustedPosition;
        }
    }
}

What it does now it's creating two walls at once it's just waiting 0.1 millisecond before creating them.

But instead i want it to show the scaling of the walls how they scaling and moving same for the else part for the adjustedPosition.z and not only the adjustedPosition.x

The problem is it's just waiting until it's placing the walls at once. I want to see the walls being building step by step like it's placing cube after cube.


texts:
I've got a large Sprite generated using a set of vertices(x,y coordinates) and a bitmap pattern (using moveTo, lineTo, beginBitmapFill, endFill ...etc). It's about 15000 pixels wide and between 1500 - 2000 pixels high depending on the level -it's the terrain for a 2D game.

My question is: what is the best way to display/move it on the stage - performance wise?

Currently I'm just adding it to the stage as is...I get decent frame rate/ memory/ cpu usage but I want to optimize it for slower PCs.
Any ideas? I've been reading a little about blitting but I'm not sure how to implement it in my case.

Thanks.


texts:
I have a wheel model. It's use Reflected Diffuse shader and only one texture and only one material. So it should seen like that, right?

But it's seen like that:

I'm really curious about that. What is the name of this technique? I want to search and learn this texturing technique but i don't know it's name.

When I add black texture on wheel material:

You see, texture is completely black. But why material not black completely? This is the question. What is the name of this technique?

Now we see with original texture:

It's really awesome.


texts: I want to use the GameJolt API, how do I protect my private key which is in my game?

texts: GameJolt is a gaming platform/website that offers API access with features like achievements tracking for users, etc. I can use the API no problem on my tests but what I'm concerned about is the private key that is issued to my game. How do I ensure that it's protected from people that want to decompile my game? Once  they get the API private key, they will be able to do anything with it.


texts: How would one determine the length of a path?

texts:
I have a game that requires each player to move along one specified path. I draw the path using Bézier curves. How can I determine the total real (not linear) length of the path and the distance that each player had made? (The distance between the start point and a specified point on the path.)

UPDATE:

The path is represented in a Cartesian plane (2D).


texts: How to align text dynamically inside a rectangle with Phaser JS

texts:
I am just starting to learn the Phaser JS framework with my first game. I did not managed to find a way how i can align text inside a rectangle element dynamically without specific coordinates. Here is what i have

pointH11L1 = game.add.text(0, 0, '20');
pointH11L1.stroke = "#000";
pointH11L1.strokeThickness = 4;
pointH11L1.font = 'oswaldbold';
pointH11L1.fontSize = 22;
pointH11L1.fill = '#999999';
//pointH11L1.alignIn(graphicsRectH12L2, Phaser.CENTER);
graphicsRectH12L2.addChild(pointH11L1);
pointH11L1.x = pointH11L1.width / 2 - 6;
pointH11L1.y = -2.5;

//graphicsRectH12L2 is the  rectangle inside which i need to align.

var graphicsRectH12L2 = this.game.add.graphics(950, 405);
    graphicsRectH12L2.beginFill(0xffcd00, 1);
    graphicsRectH12L2.drawRect(0, 0, 44, 29);
    graphicsRectH12L2.endFill(0xffcd00, 1);
    group.add(graphicsRectH12L2);


texts: Is It Possible To Make Matchmaking System Without Server?

texts:
I want to make a matchmaking system without a server, but I don't know much about matchmaking. First, let me list what I want to do:

Cheating is not important in the game, so that the architecture will be listen-server. (One of the clients in the lobby will be host.)
The players will be connected to each other by sending invitations. I will not list any lobbies in the game.
All the data in the game will be sent via RPC functions. (I have already coded this.)

The game will be published on mobile platforms. I wonder if I can connect 2 players to each other in the game without a server. Is that possible? Can I make this kind of system by using a library like socket.io?


texts:
anybody know a tutorial or maybe can help me to develop a parser/reader for JSON compatible with Unity iOS pro? I've already tried different third part libraries but without luck (i've tried json.net, jsonfx, litjson).

Im pretty in hurry of doing a simple parser/writer that i can use also under iOS and not only in Desktop.

P.s. i can also use third part library, but please, first of suggest be sure that it will work under iOS!
Thank you all


texts:
A friend and I are hoping to make a game in Unity in which you fly through an infinite 3D cave that can twist and wind in any direction (though obviously not to the point that the turns are impossible to make). We were thinking about creating a number of tunnel "pieces" that each curve a certain amount, and spawning each at the end of the one that came before.

But we have no idea how to make sure that the mouth of one tunnel piece always aligns perfectly (in both position and rotation) with the end of the previous one. Can anyone offer any advice on how to accomplish this?

Are we even going about it in the right way, or is there a better way to procedurally generate the cave? Bonus points: It'd be awesome if the cave could change in diameter and/or shape as well, though that'd just be gravy.


texts:
I want to learn C++ for game development. Does anyone know a good way to learn this?

It can be with books, tutorials, anything. I would also like to know what is a good engine to start with?

thanks you :)


texts: How costly is an OpenGL draw call, and how do I optimise them?

texts:
How costly is a draw call in OpenGL?

What are the ways to reduce the number of draw calls? I have seen people using glMapBufferRange, but I can't figure out how it improves the performance.

How much impact do draw calls have on the overall performance of a program?


texts: How to know the boundaries of an isometric tile?

texts:
In a 4x4 square tile, it's easy to know which pixels are inside the tile's boundaries. I know immediately that the 4th vertical pixel is supposed to be drawn but the 5th isn't.

However, on a rhombus' shaped tile, those boundaries aren't that obvious since the picture that contains it is a rectangle. This means that, within that rectangle, there will be pixels that are supposed to be seen and pixels which aren't.

If I'm drawing an isometric tile, how would you suggest I get to know which pixels are within its boundaries and which aren't?

I thought about drawing border lines so that I can draw the texture inside but since the texture should be a power-of-two size, there's no middle pixel on each axis, so it won't be just a matter of connecting 4 dots. So I decided to connect each of the 2 middle pixels in each edge, with the closest pixel on the closest edge (1st picture on top). However, if I draw inside of them, the texture won't reach the edge, which I imagine will create gaps. If this is the case, should I draw the lines one pixel beyond those two middle pixels in each side to get the outside boundaries (2nd image on top)? Are these lines a reliable indicator of which pixels should be seen?


texts: OpenGL strange rendering problem when buffers have different sizes

texts:
I have encountered a very odd error in my program, "odd" in the sense that everything the API says suggests that the error should not occur.

I have a bunch of 2D un-indexed vertex data, and I want to render it as lines. So far, so good. Then, I wanted to make each vertex have its own (RGB) color, so I generate a color for each vertex. For simplicity, I chose red. Works fine, except now only 2/3 of the points are being rendered! The problem arises from the fact that each vertex's position data consists of only 2 numbers, whereas the color data consists of 3 numbers. So, the "position" buffer has 2 elements per vertex while the "color" one has 3 elements per vertex. I thought that using glVertexAttribPointer to tell this information to OpenGL would be enough, but turns out it's not. In fact, if I say that the color data has only 2 elements per vertex, using

glVertexAttribPointer(vertexColorID2,2,GL_DOUBLE,GL_FALSE,0,(void*)0);

(as opposed to 3), it renders all the points - except now I can only specify two numbers for the RGB color, so I can't get the right color. The full code of the issue is below:

    glUseProgram(programID2); //draw the graph
    graph_data = graphData();
    std::vector<double> graphcolordata(graph_data.size()/2*3); for (int i = 0; i < graph_data.size(); i += 3) graphcolordata[i] = 1;
    glEnableVertexAttribArray(vertexPosition_modelspaceID2);
    glBindBuffer(GL_ARRAY_BUFFER, graphbuffer);
    glBufferData(GL_ARRAY_BUFFER, graph_data.size()*sizeof(GLdouble), &graph_data[0], GL_STREAM_DRAW);
    glVertexAttribPointer(vertexPosition_modelspaceID2,2,GL_DOUBLE,GL_FALSE,0,(void*)0);
    glEnableVertexAttribArray(vertexColorID2);
    glBindBuffer(GL_ARRAY_BUFFER, colorbuffer2);
    glBufferData(GL_ARRAY_BUFFER, graphcolordata.size()*sizeof(GLdouble), &graphcolordata[0], GL_STREAM_DRAW);
    glVertexAttribPointer(vertexColorID2,3,GL_DOUBLE,GL_FALSE,0,(void*)0);
    glDrawArrays(GL_LINES, 0, graph_data.size()/2);
    glDisableVertexAttribArray(vertexPosition_modelspaceID2);
    glDisableVertexAttribArray(vertexColorID2);

Note: programID2 is my basic shader program, and the following variable definitions were previously used:

GLuint vertexPosition_modelspaceID2 = glGetAttribLocation(programID2, "vertexPosition_modelspace");
GLuint vertexColorID2 = glGetAttribLocation(programID2, "vertexColor");

Edit: Incredibly stupid error, figured it out immediately after posting when it had previously stumped me for half an hour.

    std::vector<double> graphcolordata(graph_data.size()/2*3); for (int i = 0; i < graph_data.size(); i += 3) graphcolordata[i] = 1;

should be
        std::vector graphcolordata(graph_data.size()/2*3); for (int i = 0; i < graphcolordata.size(); i += 3) graphcolordata[i] = 1;

When this initialization is fixed, it works fine. I would delete this, but I do not see how.


texts: RNG random numbers/preset payout rate contradiction

texts:
Taking a casino slot machine for example: How can the probability of a payout TRULY be random with a preset payout rate?
If a casino has slots programmed to a specific rate or percentage of payout, how can probability of winning by RNG generated slot symbols TRULY be “random” while simultaneously being pre set by the controller?
What am I missing - Does the preset payout rate not contradict the simple and fundamental premise of random winning?
The moment preset payout rates are programmed, fundamentally you lose all chance (pun intended) of generating anything random.


texts: Unity 5 - Mouse Disappears during runtime

texts:
My mouse cursor disappears during runtime. When I click esc, it appears and the moment I click on something, it disappears again. This is what I have done so far to fix this. I have added this to a script on an empty gameobject in my scene.

void Start()
{
    Cursor.visible = true;
}

The problem persists and so I added the code to the update function. Still the same. I do not understand what am I missing here. Why is the cursor disappearing the moment I click and why doesn't it appear automatically onStart during runtime? I have also tried to implement a custom cursor and the same problem again. I am using 5.3.2f. I hope someone can point me in the right direction. Cant find a solution in any forums.


texts: Linking nodes algoritm for Visual Design

texts:
I'm developing an editor for my game, and now it's time to make a visual scripting system to let designer modify behaviours.

This video shows what i have done and the problem

to resolve the link between nodes I'm using an A* path finding,
when a path is set, I add a penalization bonus to each cell of the path, to avoid using the same cells for other path.

I would like that the lines do not intersect unnecesarily.

is there any algoritm or idea that allows me to do this better?


texts: How does one go about offering a mobile game, or offering all in-app purchases to backers?

texts:
I am planning on trying to get my android game kickstarted. Of course, it's too early in development, and I will wait on until 60% done to do the kickstarter.

Some of the rewards I am hoping to give my backers are:

The android game without having to pay
All in-app purchases unlocked for them

Since the google Play store (or other market places) would be where I would put my game up, how would I be able to reward my backers?

I could give them an apk, but I would want them to enjoy the freedom of downloading from play store, getting automatic updates, re-installing whenever they want etc.

I am hoping some of you have done something similar and can shed some light on how one goes about this?

Thank you.


texts:
I want to generate a string-code for the user that represents his progress in the game (so he can load this state somewhere else).
I don't want him to be able to guess the system and thus load a state which he hasn't yet achieved.

The following variables are involved:

A number X between 1-30 representing the highest level he unlocked.
For each level lower than X a boolean representing whether he made the level on hard or not.
For each secret object he could have found (also roughly 30) another boolean.

My idea was to just build a binary number from all these but that's just way too easy for the user to hack. If he beats level 1 and then saves, he will see his code being something like 0x1, while having bet level 10 will be something like 0x200.


texts:
I am creating a platformer game with some card base fighting. I was thinking  about how should I structure my classes? There are 2 types of cards i.e. Continuous effect and 1 time effect. Also, they can be divide into 3 other categories i.e. Environment cards, enemy cards and player cards. Please help me to get started with structuring it.

For more details, I want structure to be reusable as well as organized. Enemies and player both can interact with these cards and at some points.

Thank you


texts: Game Components, Game Managers and Object Properties

texts:
I'm trying to get my head around component based entity design.

My first step was to create various components that could be added to an object. For every component type i had a manager, which would call every component's update function, passing in things like keyboard state etc. as required.

The next thing i did was remove the object, and just have each component with an Id. So an object is defined by components having the same Ids.

Now, i'm thinking that i don't need a manager for all my components, for example i have a SizeComponent, which just has a Size property). As a result the SizeComponent doesn't have an update method, and the manager's update method does nothing.

My first thought was to have an ObjectProperty class which components could query, instead of having them as properties of components. So an object would have a number of ObjectProperty and ObjectComponent. Components would have update logic that queries the object for properties. The manager would manage calling the component's update method.

This seems like over-engineering to me, but i don't think i can get rid of the components, because i need a way for the managers to know what objects need what component logic to run (otherwise i'd just remove the component completely and push its update logic into the manager).

Is this (having ObjectProperty, ObjectComponent and ComponentManager classes) over-engineering?
What would be a good alternative?


texts: Best way to deal with a large variety of items?

texts:
I am currently working on my first java game and I am having trouble figuring out how I should implement my classes that will have heavy variety.  For example, I am considering having an abstract item class that every item in the game will inherit from, but I don't really know how specific I should get with the sub classes.  Is an armor class enough?  Should I break it down into where the armor will be equipped(head, chest, etc)?  Should I go so far as to give every single item it's own class and use a factory?

I apologize in advance for the noobie question, I have been searching around for a couple of hours but haven't been able to find a solid best practices guide that really goes in depth with this kind of stuff.


texts: Why doesn't Array.Copy to mesh.verticies work in Unity?

texts:
I am rebuilding a mesh but something seems odd that I have to create a temp array just to hold the verticies rather than copy an array.

I'm not using list because this is used frequently and I do not want to resize list and instead just use height index boundary to prevent additional  garbage collection from resizing lists.

Doesn't work and results in no mesh showing:

Mesh mesh = new Mesh();
//copy myVerticiesArray to mesh.verticies. myVerticiesArray
//length has null values above verticiesIndexHeight but array copy height set in Array.Copy()
Array.Copy(myVerticiesArray, mesh.vertices, verticiesIndexHeight);
[...] code to set UVs etc omitted
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
this.GetComponent<MeshFilter>().mesh = mesh;

Also doesn't work and results in no mesh showing:

Mesh mesh = new Mesh();
//loop through built verticies array to mesh.verticies of correct size because myVerticiesArray
//length has null values above verticiesIndexHeight
mesh.verticies = new Vector3[verticiesIndexHeight];
for(int i = 0; i < verticiesIndexHeight; i++)
{
    mesh.verticies[i] = myVerticiesArray[i];
}
[...] code to set UVs etc omitted
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
this.GetComponent<MeshFilter>().mesh = mesh;

Works and renders mesh:

Mesh mesh = new Mesh();
Vector3[] tempVerticiesArray = new Vector3[verticiesIndexHeight];
//copy built verticies array to temp array of correct size because myVerticiesArray
//length has null values above verticiesIndexHeight
Array.Copy(myVerticiesArray, tempVerticiesArray, verticiesIndexHeight);
mesh.verticies= tempVerticiesArray;
[...] code to set UVs etc omitted
mesh.Optimize();
mesh.RecalculateNormals();
mesh.RecalculateBounds();
this.GetComponent<MeshFilter>().mesh = mesh;


texts:
My map loading and rendering process is slow when using very large maps, so I'm looking for ways to make it more efficient.
My current solution works like this:

My map loader uses for loops for loading text based files and reading the map.

It parses the objects in the map and converts them to an array

The map is a text file that stores game map contents as a list of object information.

The input data looks like (x,y,z),material,blocktype (x,y,z),material,blocktype...
Scale does not need stored in the file because it's not implemented .

My rendering for loop traverses the array with a for loop

It checks if the entry in the array contains a pyramid

If so, then it calls the pyramid object's rendering method, taking other
parameters

The issue is simply slow rendering due this for loop in my OpenGL rendering code used for calling objects by checking values on arrays. It becomes slow with big objects. How can I make this faster?
I use different map loaders one for networking (receiving  player object sending info). Here's one for loading maps:
      void MapLoad(string filelocation)
      {

            string[] map_;

            string line = File.ReadAllText(filelocation);//
            map_ = line.Split(new char[] { ',', ';', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

            for (int xj = 0; xj < map_.Length; xj += 5)
            {
                // Here xj is an index of a X coordinate, xj + 1 is an index of a Y coordinate, xj + 2 is an index of a Z coordinate

    //object for storing the data
                    Block_ chunk_block = new Block_();
    //coordinates set
                    chunk_block.set_v1(new Vector3(Int32.Parse(map_[xj]), Int32.Parse(map_[xj + 1]), Int32.Parse(map_[xj + 2])));
    //material set
                    chunk_block.set_v1_material(Int32.Parse(map_[xj + 3]));//1
    //block type set
                    chunk_block.set_v1_blocktype(Int32.Parse(map_[xj + 4]));
                    chunk_block.set_v1_scale(new Vector3(1, 1, 1));
                    stuff__.block_file.Add(chunk_block);
                    stuff__.collision.Add(chunk_block.get_v1());

            }

        }

    //version for position
    void MapLoad(string filelocation,Vector3 position)
    {

            string[] map_;

            string line = File.ReadAllText(filelocation);//
            map_ = line.Split(new char[] { ',', ';', '(', ')' }, StringSplitOptions.RemoveEmptyEntries);

            for (int xj = 0; xj < map_.Length; xj += 5)
            {
                // Here xj is an index of a X coordinate, xj + 1 is an index of a Y coordinate, xj + 2 is an index of a Z coordinate

                Block_ chunk_block = new Block_();
    //position
                chunk_block.set_v1(new Vector3(Int32.Parse(map_[xj])+position.X, Int32.Parse(map_[xj + 1]) + position.Y, Int32.Parse(map_[xj + 2]) + position.Z));
    //mat
                chunk_block.set_v1_material(Int32.Parse(map_[xj + 3]));//1
    //blocktype
                chunk_block.set_v1_blocktype(Int32.Parse(map_[xj + 4]));
                chunk_block.set_v1_scale(new Vector3(1, 1, 1));
                stuff__.block_file.Add(chunk_block);
                stuff__.collision.Add(new Vector3(chunk_block.get_v1().X, chunk_block.get_v1().Y+1, chunk_block.get_v1().Z));

            }

        }

And here is my rendering loop:
for (int i = 0; i < stuff__.block_file.Count; i++)
{
        //block data given to block model object that takes material for textures etc but thats not about problem
        block(new Vector3(stuff__.block_file[i].get_v1().X, stuff__.block_file[i].get_v1().Y-2 + walking__, stuff__.block_file[i].get_v1().Z), stuff__.block_file[i], BeginMode.Quads, stuff__.block_file[i].get_v1_scale());
}


texts: How to calculate new velocities between resting objects (AABB) after accelerations?

texts:
lately I have been trying to create a 2D platformer engine in C++ with Direct2D. The problem I am currently having is getting objects that are resting against each other to interact correctly after accelerations like gravity have been applied to them.

Right now I can detect collisions and respond to them correctly (I think) and when objects collide they remember what other objects they're resting against so objects can be pushed by other objects (note that there is no bounce in any collisions so when objects collide they are guaranteed to become resting until something else happens). Every time the simulation advances, the acceleration for objects is applied to their velocities (for example vx += ax * t, where t is time elapsed since last advancement).

After these accelerations are applied, I want to check if any objects that are resting against each other are moving at different speeds than their counterparts (as different objects can have different accelerations) and depending on that difference either unlink the two objects so they are no longer resting, or even out their velocities so they are moving at the same speed once again. I am having trouble creating an algorithm that can do this across many resting objects.

Here's a diagram to help explain my problem


texts: Accelerometer to move player left and right

texts:
Please take a look on my code and help me to find problem.

I used this tutorial: COCOS2D_ACCELEROMETER_MOVEMENT
This works only sometime….some time not move..How can I resolve this problem?
Here is my sample: DOWNLOAD
Thanks for reading this…what's wrong with my code ? Is there any other way?

Here is my code:

#define kHeroMovementAction 1
#define kPlayerSpeed 500
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    // use the running scene to grab the appropriate game layer by it's tag

    // grab the player sprite from that layer using it's tag
    CCSprite *playerSprite = mPlayer;
    float destX, destY;
    BOOL shouldMove = NO;

    float currentX = playerSprite.position.x;
    float currentY = playerSprite.position.y;

    if(acceleration.x > 0.25) {  // tilting the device upwards
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else if (acceleration.x < -0.25) {  // tilting the device downwards
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else

        if(acceleration.y < -0.25) {  // tilting the device to the right
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else if (acceleration.y > 0.25) {  // tilting the device to the left
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else {
        destX = currentX;
        destY = currentY;
    }

    if(shouldMove)
    {
        CGSize wins = [[CCDirector sharedDirector] winSize];
        // ensure we aren't moving out of bounds
        if(destX < 30 || destX > wins.width - 30 || destY < 30 || destY > wins.height - 100) {
            // do nothing
        } else {
            CCAction *action = [CCMoveTo actionWithDuration:0.5f position: CGPointMake(destX, playerSprite.position.y)];
            [playerSprite stopActionByTag:kHeroMovementAction];
            [action setTag:kHeroMovementAction];
            [playerSprite runAction:action];
        }
    } else {
        // should stop
        [playerSprite stopActionByTag:kHeroMovementAction];
    }

}


texts:
I would like to know the best way on how to implement horizontal scrolling to only part of the view and vertical scrolling to complete view. I was able to achieve horizontal and vertical scrolling to the complete view. If I have to use layers can you explain a bit more on how to achieve layers and draw shapes on those layers separately.

I tried using two different SurfaceViews it does not work. Here is my code for scrolling horizontally.

@Override public void onDrawFrame(GL10 unused) {

GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

// Set the camera position (View matrix)
Matrix.setLookAtM(mVMatrix, 0, mXOffset, mYOffset, -3, mXOffset, mYOffset, 0f, 0.0f, 1.0f, 0.0f);

// Calculate the projection and view transformation
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mVMatrix, 0);

mGraph.draw(mMVPMatrix);

mLine.draw(mMVPMatrix);
msquare.draw(mMVPMatrix);

}


texts: Am I allowed to release a fan-made version of a Trading Card Game on a fansite?

texts:
Consider a Trading Card Game that is currently available for play in digital format only, the game in question would be HEX: Shards of Fate, but this question is intended as a general question about all Trading Card Games.

Now my idea is to create an AI player for that game and see how good it performs. For this I'll need to build a client that is capable of playing the game and initially I want to test it myself and distribute it to a few friends so they can play around with it.

I am myself unsure of whether the EULA specific to this game are of any importance, as I believe all games will try to protect their games to the fullest extent as possible. However we also know that there are fansites out there which are allowed (are they legally allowed?) to display the cards of the game (including artwork) as long as they have a clear reference to the game which it is about and they do not attempt to make any money out of the cards themselves. I do believe that premium services on a fansite itself are legal.

Ultimately I want to create a fansite where:

There is an obvious reference that the cards, etc. belong to the company that created the game.
You can as player play versus an AI, using a game interface that is similar to the one that is in the actual digital version. It most likely won't be an exact 1:1 copy and some substitute interface will be used that doesn't look as nice.
Playing versus the AI is not promoted as an actual game, it is just a site where you can test your skill as player, and as creator I can test the effectiveness of the AI.
All cards are freely available to any player, I most surely do not intend to monetize that part.
There is possibly a premium service that offers benefits, possibly more detailed statistics or more AI matches, more options, etc.

So I've got the following questions about this:

Is the limited distribution amongst myself and friends legal?
Is this fansite legal without the premium service?
Is the premium service legal?
Would selling booster packs (where you can obtain the cards) and having the player start with a minimal collection actually be illegal?


texts:
Im trying to get a list of vectors that go around a circle, but i keep getting the circle to go around several times. I want one circel and the dots to be placed along its circumference. I want the first dot to start at 0 and the last dot to end just before 360. Also i need to be able to calculate the spacing by the ammount of points.

  List<Vector2> pointsInPath = new List<Vector2>();
    private int ammountOfPoints = 5;
    private int blobbSize = 200;
    private Vector2 topLeft = new Vector2(100, 100);
    private Vector2 blobbCenter;
    private int endAngle = 50;
    private int angleIncrementation;
    public Blobb()
    {
        blobbCenter = new Vector2(blobbSize / 2, blobbSize / 2) + topLeft;
        angleIncrementation = endAngle / ammountOfPoints;

        for (int i = 0; i < ammountOfPoints; i++)
        {
            pointsInPath.Add(getPointByAngle(i * angleIncrementation, 100, blobbCenter));
          //  pointsInPath.Add(getPointByAngle(i * angleIncrementation, blobbSize / 2, blobbCenter));
        }
    }

    private Vector2 getPointByAngle(float angle, float distance, Vector2 centre)
    {
        return new Vector2((float)(distance * Math.Cos(angle) ), (float)(distance * Math.Sin(angle))) + centre ;
    }


texts: How can I adapt A* pathfinding to work with platformers?

texts:
I have an A* implementation that works in "top down" situations where gravity is not taken into account for pathfinding. But, I am looking to modify to work in a 2d platformer situation. I am using the Unity Engine in C# but any examples or even pseudocode would be really helpful. I have found a source so far but it haven't been that helpful as I am not understanding the way they have adapted A*, I have listed them below.

http://gamedevelopment.tutsplus.com/tutorials/how-to-adapt-a-pathfinding-to-a-2d-grid-based-platformer-theory--cms-24662 (Very specific to authors implementation and hard to understand)


texts:
Should I install Android Playback Engine in Unity if I am going to make games for Android? What the Android Playback Engine is used for?

I got the question when decided to reinstall Unity and met it:

I tried to figure out what it is used for on my own, but found almost nothing. It seems that I am a bad seeker. I found just this:

Movie playback

Movie textures are not supported on Android, but full-screen streaming playback is provided via scripting functions.

Is it just about showing you the game backwards? (з


texts: Accessing the child sprites of a sprite sheet in unity?

texts: I have a spritesheet set up with the individual sprite regions named in unity. I haven't been able to find out how to access these sprites by name?


texts: Calculating up-vector to avoid gimbal lock using euler angles

texts:
I wish to orbit a camera around a sphere, yet the problem is that when the camera rotates so that it is at the north pole (and pointing down) or the south pole (and pointing up) of the sphere the camera doesn't handle itself very well. It spins rapidly until arriving 180 degrees in the opposite direction. I believe this is known as gimbal lock.

I understand you can avoid this problem using quaternions. But I also read in another forum that it's possible to avoid this easily using euler angles as well. Which I would prefer to do. It was said that all you need to do is "calculate a proper up-vector every frame, and that avoids the problem entirely."

Well, I tried aligning the up-vector with the vertical axis of the camera whenever the camera changed orientation, but this didn't seem to work. Meaning that the up-vector followed exactly the orientation of the camera's y-axis (or it's up vector), instead of using a constant up-vector aligned to the up-vector of the world (0, 1, 0).

How exactly do I go about calculating a proper up-vector as my camera orientation changes to avoid the gimbal lock problem mentioned above?


texts: Extracting Frustum Planes (Hartmann & Gribbs method)

texts:
I have been grappling with the Hartmann/Gribbs method of extracting the Frustum planes for some time now, with little success. There doesn't appear to be a "definitive" topic or tutorial which combines all the necessary information, so perhaps this can be it

First of all, I am attempting to do this in C# (For Playstation Mobile), using OpenGL style Column-Major matrices in a Right-Handed coordinate system but obviously the math will work in any language.

My projection matrix has a Near plane at 1.0, Far plane at 1000, FOV of 45.0 and Aspect of 1.7647.

I want to get my planes in World-Space, so I build my frustum from the View-Projection Matrix (that's projectionMatrix * viewMatrix). The view Matrix is the inverse of the camera's World-Transform.

The problem is; regardless of what I tweak, I can't seem to get a correct frustum. I think that I may be missing something obvious.

Focusing on the Near and Far planes for the moment (since they have the most obvious normals when correct), when my camera is positioned looking down the negative z-axis, I get two planes facing in the same direction, rather than opposite directions. If i strafe my camera left and right (while still looking along the z axis) the x value of the normal vector changes.

Obviously, something is fundamentally wrong here; I just can't figure out what - maybe someone here can?

EDIT: Applying the algorithm to just the Projection matrix (i.e. model and view matrices are identity) I get the Near and Far planes returned as the following;
Far:  normal[0,0-1],  distance 1
Near: normal[0,0,-1], distance -0.3328891

Can someone tell me if these seem correct? Using the algorithm with just the Projection Matrix should return the planes in View Space (camera space)


texts: Object movement to a circular shape, with the grab of a VR controller?

texts:
I have a HTC Vive VR set, which has a controller. I have a sphere object, which I want to rotate in a circular motion around my VR Player object, based on the controller grab and its movement. The controller should first grab the object, then it will move left or right, in a circular motion, based on the controller movement. How can I achieve this?

So far, I have made a sphere, with a parent. The parent position is updating with respect to my camera head, so I can move my sphere with my player. The sphere object should move with the controller, but in a circular motion. This has not been achieved, yet, and I really don't know how to do it.

I am able to grip the sphere object using a VRTK script, and I can freely move it, but I want to restrict its movement; much like in the illustrated figure, below:


texts: How to make sure that all the UI elements were the same size on all screens in new Unity 4.6 UI system

texts: I have made a HUD for my 2d mobile game with the help of the new UI system, that was introduced in Unity 4.6. But when I am trying to play game in Unity editor, the UI elements have normal size, but when I am playing this game on mobile devices, they have more small size than in editor. Why this is happening? May be I missed something while watching Unity tutorials about new UI system. Can anyone help me please.


texts: Handle many lights in a scene (with shaders)

texts:
I'm curious about how to handle many lights in a scene. Given a very big map in a role playing game, with dungeons (with lights in there) etc. I know about deferred lighting, but that only answers how to render many lights. But my question is more: How to not render many lights. It's obviously desirable to only render the lights effecting the scene, but I don't know a technique/an algorithm to archive this. Nobody wants or is even able to render 500 point lights, just because there somewhere in the map. But one cannot just take a straight line from the light to the player and test if something is in between. The distance also doesn't seem like a good indicator. (Sunlight?)

tl;dr: How can I figure out which lights affect the scene to only render them?


texts:
I'm designing an MMOFPS.  I'm not sure whether to use one UDP port for all clients or one UDP port per client.  Or is there another alternative?

Currently UDP is only being used for position data (X,Y,Z, heading, and pitch).


texts:
I have found other questions like this, but none seem to quite cover the situation I have.

I am using DirectX 11

I have an object that has:

Position (vector)
Rotation (quaternion)
View angle (pitch, roll, yaw)

The view angle needs to be added to the rotation in order to know the true view rotation. You can think of view a head, and rotation as body.

I want to be able to turn the head so that it looks at a given point in space (vector)

The head needs to move slowly so I need to workout what way to turn and then move the head in that direction in small amounts. (pitch, yaw, roll) units

I have attempted to get this working but I don't even seem to be able to get close to what I need.

Thanks in advance.


texts:
I'm trying to use PhysX for my physics engine.  I'd like to use spherical joints, but I'm having trouble with the constraints.  All of the examples that I've found refer to SDK v2.8.  I'd like to stick with v3.0.  Even the PhysX support center uses deprecated APIs.  There's a tutorial at the support center (Ch 4 - Grass) that I'm trying to imitate.  Converting that code to the current API has been problematic.  NxSphericalJointDesc is deprecated.  How do you specify equivalent constraints to those found in the tutorial?

There's another post that talks about a similar problem.


texts: I have a parameter in HLSL shader in a constant buffer which is a float3x3. Is there is 3x3 matrix struct in Directx 11 or should I use 4x4 matrix instead, and if so, how?


texts:
I've been working on an RPG videogame, and I have been trying to implement a Save button into my game, which is supposed to save the player's itemAmount variable, which is in another script, called ItemInformation. I retrieve the itemAmount variable at Start() by getting the script from the itemHolder GameObject. I plan to use this script in multiple GameObjects, because I use the same variable (itemAmount) with different values in different GameObjects. For some reason, I don't receive any errors or warnings in the Console. Here is my script to the Saving System:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class InventorySave : MonoBehaviour
{
    // Public variables for inventory and health
    private GameObject itemHolder;
    private ItemInformation myItemAmount;

    // Initiates before the first frame
    void Start()
    {
        // Gets components for the player variables
        itemHolder = transform.gameObject;
        myItemAmount = itemHolder.GetComponent<ItemInformation>();
    }

    // Function that will be called when player saves game from pause menu
    public void SaveGame()
    {
        // Creates file to store variables
        BinaryFormatter bf = new BinaryFormatter();
        FileStream file = File.Create(Application.persistentDataPath + "/SaveData.dat");
        SaveData data = new SaveData();

        // Gets the player data
        data.itemSave = myItemAmount.itemAmount;

        // Writes player data to file and encrypts it
        bf.Serialize(file, data);
        file.Close();
    }
}

// Holds data that is to be saved
[Serializable]
class SaveData
{
    // Variables for save file
    public int itemSave;
}


texts: Road network geometry in Unity: one big mesh or a bunch of smaller meshes?

texts:
I'm in the beginning stages of building a road system in Unity. It'll be your basic SimCity style road construction, with building and destroying roads done on the fly at runtime. When doing thing, given the fact that geometry will be so often added and destroyed, should I keep a separate mesh for each segment of road, or should I maintain one big road mesh for the whole scene and add and remove vertices to it when roads are modified? In larger road networks would there be any performance difference between the two? I'm not so familiar with this sort of optimization in Unity, so any help is appreciated.

So basically, many small meshes or one big mesh? Does it matter?


texts: Most efficient way to generate 2D portraits

texts:
I am not sure if this is a fitting question for gamedev, or if it is too art related. I am currently trying, to create 2D character protraits for my game.

At first I tried to draw them and even though it helped polishing my drawing skills the end result either required way too much time or it simply looked like it was created by a grade school kid.

So I am currently looking into some tools which from which people like me who are not out of the art-world might benefit. Especially tools which can create a 3D head+hair, so that I can render them.
I have tried several 3D generation tools such as makehead and makehuman to create the basic head-shape.

But I have to admit I am not well versed in what other options are available/what has the best quality/etc.


texts: How to load and unload objects at a certain radius from the player?

texts:
I am making a procedurally generated space exploration game in unity. I'm currently generating 5000 stars in a cube of a fixed size. Each star just gets a random 3d coordinate. What I would like to do is to dynamically load and unload stars at a certain radius from the player. This would be the maximum view distance. The algorithm that does this must be working with a seed for the universe, as the stars need to be loaded in the same spot when you revisit them.

My idea is something like in the amazing Space Engine.

I have pretty much no knowledge of algorithms that can do this, so I ask for your help.


texts:
Usually, when discussing on performance in games, cache misses and localities come like the real problem. But i feel like videogames are too focus optimization in that way.

For example, the author of this blog entry talks on how essential is a good datastructure to achieve high performance. But out of a situation where you have many entities that will stay on movement almost always, i cannot come with an example where these optimizations can help:

Handling the player inventory is a inherently a complex task. You are not going to iterate every inventory to check whether or not an entity wants to retrieve/add an item from/to its inventory.
Combat is usually intensive and fast, but from the perspective of the cpu, not frequent. Not every entity will be slashing and definitely not every frame.
AI is another good example where you hardly can optimize using big arrays of data. In starcraft linked list were used:

  Linked lists were used extensively in the engine to track units with shared behavior. With twice the number of units of its predecessor — StarCraft had a maximum of 1600, up from 800 in Warcraft 2 — it became essential to optimize the search for units of specific types by keeping them linked together in lists.

So, my question is: Is the cache friendly approach to optimize games wrong or misused?


texts: Make a laser beam effect with Ogre and a BillboardChain

texts:
http://www.lpi.usra.edu/lunar/missions/apollo/apollo_15/images/laser_beam_lg.gif

I want to be able to such an effect, but I don't really know how the BillboardChain class works or how I can use it, examples for this class seems to be rare.


texts: Is there any equivalent to glPushMatrix in XNA?

texts:
I'm trying to implement a scene graph for my 2D game in XNA, and I was looking for a way to draw every object while saving only the local transformation of the object. This seems a bit like glPushMatrix. If such a function exists I can just push a matrix for every node and then call the draw function for all its children.

The whole idea is to avoid passing parent transformations to children. Is there anyway to do so?


texts: Is it possible to make desktop visible behind drawn object using SDL2?

texts: I would like to draw an avatar over the desktop, something similar to those word 97 assistants, my idea so far is to make only the background transparent but I haven't had any luck, any suggestion? is it possible to make with SDL2?


texts: Simulation step size in a physics engine

texts:
I am trying to integrate a physics engine (Bullet) into my game engine, but I immediately found that I do not know how big should I make the simulation step. I think of 2 options:

Use a fixed step size of 1/60. This way I have consistent simulation. Bullet allows making multiple steps when this time is exceeded. I think this is good for consistent simulation but I think it has a big flaw and that is that position of objects will not update when my framerate is higher than 60FPS. Right now I have around 1000 FPS but it will drop significantly to around 150 I expect because I use simple materials and not many objects plus the simulation time is not included yet. Is it possible to interpolate between steps so that 2 frames are always different but check for collisions only when 1/60 of a second passed?

Update physics every frame but when frame time is longer than 1/60 then use substeps. This way I should be able to get more precision but it would lower framerate because the step is performed more than 60 times per second. I definitely get the new position of the object in every frame.

Which is a better approach and why? Is there a standardized way to go about it?
I know that when slow-motion footage of CSGO is taken in every frame the position of the object change but the tick rate is just 64. Which would not update the position in every one of the 240 frames monitors can handle and duplicate frames would be created. I know that animation can be sampled at any point in time but not the position of the objects. How is that achieved?


texts:
I am making an RTS game which currently has a very heavy GUI and takes up sometimes 50% of the CPU time per frame.
Most of the data on the GUI remains constant, (selected units and their avalible actions) but some needs to be updated frequently (health bars, progress bars).

Is it possible to draw the GUI once on an event and then keep that on screen and only redraw parts of the GUI?


texts:
could someone explain to me why i can't get a new position that is outside the update method.

if i set what's inside the void callposic to a Start I can't get any position, only if it's inside the update

what can you do, because I don't want to use them in the update board.

https://www.youtube.com/watch?v=aNzJ5GUYAOA&feature=youtu.be

public int index;
public Vector3[] posic;
void Start()
{
    prev.onClick.AddListener(() => void1(-1));
    next.onClick.AddListener(() => void1(1));
    index = 0;

}

void Update()
{
    callposic();
}

void callposic()
{
    transform.localPosition = posic[index];
}

void void1(int value) { index = index + value; }

}


texts:
I'm attempting to play with graphics using Java/Slick 2d. I'm trying to get my sprite to rotate to wherever the mouse is on the screen and then move accordingly. I figured the best way to do this was to keep track of the angle the sprite is at since I have to multiply the cosine/sine of the angle by the move speed in order to get the sprite to go "forwards" even if it is, say, facing 45 degrees in quadrant 3. However, before I even worry about that, I'm having trouble even getting my sprite to rotate in the first place. Preliminary console tests showed that this code worked, but when applied to the sprite, it just kind twitches. Anyone know what's wrong?

int mX = Mouse.getX();
    int mY = HEIGHT - Mouse.getY();
    int pX = sprite.x;
    int pY = sprite.y;
    int tempY, tempX;
    double mAng, pAng = sprite.angle;
    double angRotate=0;

    if(mX!=pX){
        tempY=pY-mY;
        tempX=mX-pX;

        mAng = Math.toDegrees(Math.atan2(Math.abs((tempY)),Math.abs((tempX))));
        if(mAng==0 && mX<=pX)
            mAng=180;
    }
    else{
        if(mY>pY)
            mAng=270;
        else
            mAng=90;
    }

    //Calculations
    if(mX<pX&&mY<pY){ //If in Q2
        mAng = 180-mAng;
    }
    if(mX<pX&&mY>pY){ //If in Q3
        mAng = 180+mAng;
    }
    if(mX>pX&&mY>pY){ //If in Q4
        mAng = 360-mAng;
    }

    angRotate = mAng-pAng;
    sprite.angle = mAng;

    sprite.image.setRotation((float)angRotate);


texts: I wanted to let the player rename the character of my game. So I thought that making a text box and when he clicks the ok button, the text inside the text box will make it to a string and render it on the screen. How do I let the user type their own text?


texts: LibGDX Drawing sprites when moving orthographic camera

texts:
I've been having this problem for a long time and I just can't seem to find the exact problem. I have a game where the map is 480x1600 and my camera has a view of 480x800. I have a button that when pressed, allows the user to place a platform on the map, and since the map is too big to fit on the screen, I made it so the user can move the camera up and down the map by dragging.

@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    cam.position.y = pos.y;
    return true;
}

Method that controls when the user tries to put a platform down

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector3 pos = new Vector3(screenX, screenY, 0);
    cam.unproject(pos);
    Gdx.app.log(Game.LOG, "X Coordinate: " + pos.x + " Y Coordinate: " + pos.y);

    if (GameScreen.createPlatform == true) {
        world.setPlatform(new Vector2(pos.x - 0.6f, pos.y - 0.1f), 1);
        GameScreen.createPlatform = false;
        return true;
    }

    ...
}

Where I render the platform sprites

public void render(float delta) {
    ...
    spriteBatch.setProjectionMatrix(cam.combined);
    spriteBatch.begin();
    for (Sprite platformSprite: world.getPlatformSprites()) {
        platformSprite.draw(spriteBatch);
    }
    spriteBatch.end();
    ...

}

The game works fine when I don't move the camera. But when I do, the platforms aren't placed where I click, they're always either higher or lower where I actually clicked. Also, the platforms are always placed somewhere where the camera was originally looking before anything has been moved.

I think it's doing this is because for some reason, the coordinates never actually change. So wherever I am on the map, the top of the screen is always 120 and the bottom is always 90. This also causes objects on the map to have different coordinates if I move the camera.

This problem has me completely lost and I would appreciate any help.


texts: Associate a texture to an object (from a data-model, not graphical point of view)

texts:
I'm writing a roguelike where objects and floor can be made of different materials. For instance, let's say we can have a wooden chair, an iron chair, a golden chair, and so on.

I've got an Object class (I know, the name is terrible), which is more or less using a composite pattern, and a Material class. Material have different important properties (noise, color...). For the time being, there are 5 different instances of materials, created at the initialization of the game.

How would connect an instance of Object with one of the 5 instances of materials ? I see three simple solutions :

Using a pointer. Simple and brutal.
Using an integer material-id, then get the materials out of a table when engine manipulates the object for various purposes (display, attack analysis, etc.). Not very beautiful, I think, and not very flexible.
Using an integer material-id, then get the materials out of a std::map. A bit more flexible, but still not perfect.

Do you see other possibilities ? If not, what would you choose (and why) ? Thanks in advance !


texts: Learning To Create Better Art (2D Games)

texts:
Until one of my games "makes it" big, or I get flooded with gold ingots, I will have to handle most or all of my game art myself. The crux of my question is: how can I learn enough art to get beyond "programmer art" and into something I would actually be proud of?

The focus of my question is 2D, not 3D.

I already have a good grip on:

Photoshop/GIMP (image maniplation and creation)
Flash (animation and drawing simple art)
Simple drawing (by hand)
Digitizing hand-drawn art
Graphic design

However, games require complex and varied art; anything from backgrounds to icons, sprites, animation, and complex effects.

How do I bridge the gap, artistically?  I already have the experience and confidence that I can do it; I only need to know the direction in which to put my modest efforts. I know this will pay off, especially in the long term. But I'm not sure how to get there.

Using existing art is something I already do, so please don't address that in your question.


texts:
As a newbie to iOS programming, I'm wondering which of these would be more conducive to the type of game I want to program. I've been tasked to program an iOS game for my company. They asked me to do this after learning I was studying some Swift on my own time.

The game will be a turn-based strategy game consisting of a map with irregular areas/polygons and player pieces that can be moved on the map. I'll need to be able to detect when a piece moves into different areas and restrict a piece to moving only a certain number of areas per turn.

Can this be accomplished in straight Swift/Spritekit?


texts: States, actions logic am I doing it right?

texts:
Currently I have the follow states:

Need To Run
Run
Need To Walk
Walk
Need To Fight
Fight

Am I misunderstanding it and mixig possible actions with states ?

I mean, to me Need To Run would either return true of false telling wether I should procced to the Run action or not and same goes for the other needs.

While I am fighitng should I have second FSM to threat what skills it should be using for example if it needs to heal or not ?

For instance inside the fight I would have the another FSM for

Need To Heal
Heal
Back To Fight
Use Skill


texts:
I'm working on an RPG and I'm trying to figure out how to manage the different levels/areas in the game. Currently I create a new state (source file) for every area, defining its unique aspects. My concern is that as the game grows the number of class files will become unmanageable with all the towns, houses, shops, dungeons, etc.  that I need to keep track of.

I would also prefer to separate my levels from the source code because non-programmer members of the team will be creating levels, and I would like the engine to be as free from game specific code as possible.

I'm thinking of creating a class that provides all the functions that will be the same between all the levels/areas with a unique member variable that can be used to look up level specifics from data. This way I only need to define level/area once in the code, but can create multiple instances each with its own unique aspects provided by data.

Is this a good way to go about solving the issue? Is there a better way to handle a growing number of levels?


texts: back-face (back-line) culling without winding order

texts:
In fooling around with my own 3D display engine I've been able to get a few modest features working, and I've come close with this latest one - line culling - but I fear in order to do it correctly I'll need to backpedal a little bit and start establishing more attributes in my basic wireframe objects. I'd like to avoid that if possible because I legitimately haven't needed it until now (maybe).

The basic '3d object' class is essentially just lists of lines, points, an RGB value for color, and a few self-transforming methods for basic movement and rotation.

class MyObject(object):
    def __init__(self, points, lines, color):
        self.points = points
        self.lines = lines
        self.color = color
    # insert methods for rotation/translation/etc

No vertex order, no collection of 'faces' or 'sides' or anything, just points and lines and a color.

I've tried to introduce a culling method into my view object that uses all the possible triangles that each line could be an edge with, and then checks the dot product of that triangle's outward-facing normal against the imaginary line from the camera to the shared point in the triangle (v0, pt_a, etc).

def line_cull(self, shape):
    """Determine which lines should be drawn by comparing them against
    the triangles they could be a part of. If the triangle faces away from the
    camera, don't draw that line.
    """
    to_draw = []
    for line in shape.lines:
        a, b = line
        # get a list of the other lines that point a exists in
        other_lines = [m for m in shape.lines if a in m and m is not one]
        # treat point a as "vertex 0" and get the line from a to the camera
        a_to_cam = minus(a, self.camera)
        for line2 in other_lines:
            # get the correct point c
            if not a == line2[0]:
                line2 = line2[::-1]
            c = line2[-1]
            # get the vector of ab and ac for a cross product
            ab = minus(b, a)
            ac = minus(c, a)
            # find the middle of the triangle
            mid = [x / 3.0 for x in plus(a, plus(b, c))]
            # outwards is the direction vector from the shape's center
            # to the middle of the triangle. for whatever reason this
            # has been working better at orienting the normal than just
            # using the dot product to the center of the object
            outwards = minus(mid, shape.center)
            norm = cross(ab, ac)
            if dot(norm, outwards) < 0:
                norm = cross(ac, ab)
            if dot(norm, a_to_cam) < 0:
                if line not in to_draw:
                    to_draw.append(line)
    return to_draw

This works for certain shapes a lot better than others. Sticking to platonic solids for now - tetrahedrons and cubes are perfectly drawn, whereas octahedrons (especially rotating ones) have flickering back-end lines.

I did try to include a line about confirming the existence of line BC -- that is, the imaginary 'third line' in the triangle -- and all of a sudden, all my cubes disappeared! Because there would never be a third line in its series of right-angles, and so there was nothing to render anymore.

My question is -- do I have to establish faces/sides/etc in order for this to "just work", or is there a way to suss out which pairings should not be considered, without just excluding certain shapes from being rendered at all?


texts:
I really need the help of an expert. I'm trying to rotate an object in all 3 axes relative to the camera in response to the gamepad sticks. I have succeeded but with an unexpected error, depending on its orientation, the object can rotate in the opposite direction of the stick direction.
For example, if the object is on its back, when I move the stick to the left the object rotates to the left. But, when the object is facing the camera, when I move the stick to the left the object rotates to the right. The same happens in all 3 axes, on each axis I have 180 degrees with the correct stick orientation and 180 degrees with inverted sticks. Also, both the camera and the object can freely move adding more complexity to this problem.
I would like to find a way where the orientation of the rotation always follows the direction of the stick. This is solved with a minus sign applied to the angle according to the object orientation (relative to the camera) but I can't find out how.
This is the code I'm using, it works fine except for the orientation problem. Can anyone find the solution to this problem?
public void ObjectRotate(int dir, float angle) // Object is defined elsewhere
{
    var rotate = 360 * Time.deltaTime * angle;
    var target = Object.transform;

    if(dir == 1) { target.RotateAround(target.transform.position, Camera.main.transform.right,  rotate ); }
    else if(dir == 2) { target.RotateAround(target.transform.position, Camera.main.transform.up, rotate); }
    else if(dir == 3) { target.RotateAround(target.transform.position, Camera.main.transform.forward, rotate); }
}


texts: Compiling 2 Dimensional Constant Arrays Right into Pixel Shader to use as Lookup Table

texts:
I want to use a small 2 dimensional look up table in a fragment shader, but I don't want to pay for the performance cost of fetching it from memory for every fragment.

Is it feasible/reasonable to simply declare or hardcode the table as an array right inside the fragment shader?  If yes, any indicator as to how big I can make it?

Thanks,
- Jim


texts:
I'm working on a project for school and I'm having some trouble solving a bug.
When the player collides with a rectangle the sprite/hitbox keeps jittering while the player has momentum in the direction.

I'm guessing that the reaction sometimes moves it so that they are right next to each other and sometimes it makes it so that there is a 1 pixel space between. Is this because I'm using float and it sometimes rounds up? If so what is a good way to solve it?

The order it happens in gameloop is:

Update player position
Check collision (move if there is one)
draw player to window

The code I use for collision detection and reaction is:

void Collider::collisionTest(Player &player, sf::RectangleShape &rec2, float push) {
    float intersectX;
    float intersectY;
    float deltaX;
    float deltaY;

    if(AABBCollision(player.getHitbox(),rec2, intersectX, intersectY, deltaX, deltaY))
    {
        push = std::min(std::max(push,0.0f), 1.0f);

        if(intersectX > intersectY){
            if (deltaX > 0.0f){
                player.playerMoveCollision(intersectX * (1.0f - push), 0.0f);
                rec2.move(-intersectX * push, 0.0f);
            }else
            {
                player.playerMoveCollision(-intersectX * (1.0f - push), 0.0f);
                rec2.move(intersectX * push, 0.0f);
            }
        }else{
            if (deltaY > 0.0f){
                player.playerMoveCollision(0.0f,intersectY * (1.0f - push));
                rec2.move(-intersectY * push, 0.0f);
                player.setIsJumping(false);

            }else
            {
                player.playerMoveCollision(0.0f,-intersectY * (1.0f - push));
                rec2.move(0.0f, intersectY * push);

            }
        }

    };

}

bool Collider::AABBCollision(sf::RectangleShape& rec1, sf::RectangleShape& rec2, float& intersectX,float& intersectY,float& deltaX,float& deltaY) {
    sf::Vector2f rec1Position = rec1.getPosition();
    sf::Vector2f rec1HalfSize = rec1.getSize() * 0.5f;
    sf::Vector2f rec2Position = rec2.getPosition();
    sf::Vector2f rec2HalfSize = rec2.getSize() * 0.5f;

    deltaX = rec2Position.x - rec1Position.x;
    deltaY = rec2Position.y - rec1Position.y;
    intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
    intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);

    if (intersectX < 0.0f && intersectY < 0.0f){
        return true;
    }
    return false;
}

Edit:

So i kinda solved it in whats probably a bad way.

The problem was using abs(deltaX/deltaY) as i shaved off the decimal point of the float.

What i did to solve it was:

intersectX = abs(deltaX) - (rec2HalfSize.x + rec1HalfSize.x);
intersectY = abs(deltaY) - (rec2HalfSize.y + rec1HalfSize.y);

into

if(deltaX < 0)
{
    intersectX = (deltaX * -1) - (rec2HalfSize.x + rec1HalfSize.x);
}else
{
    intersectX = deltaX - (rec2HalfSize.x + rec1HalfSize.x);
}

if(deltaY < 0)
{
    intersectY = (deltaY * -1) - (rec2HalfSize.y + rec1HalfSize.y);
}else
{
    intersectY = deltaY - (rec2HalfSize.y + rec1HalfSize.y);
}


texts: What is the interval of fragment-shader code execution?

texts: Without any intended delay, is the code of a fragment-shader run once per frame? If not, how often will the code be executed? (I'm new to shaders: I'm talking about glsl if it makes any difference)


texts:
In the first code I get a Vector2 random position and create an object with that, but in the second code I want to use the same constructor to create an object, but I want to pass a X and Y value to the constructor, that expects a Vector2 value.

Vector2 newPosition = NewRandomPosition;
listTools.Add(new Tool(content, tools[i], newPosition));

I thought I could do something like this, but it didn't work!

int x = 30, y = 22;
listJunk.Add(new Junk(content, "junk", (x,y)));

Is there another way to do this? Thanks!


texts: Do we really need quaternions? In UE4 I rotate without them

texts: I want to experience gimbal lock to be able to understand how it happens. In lots of videos it shows that when you rotate along one axis, other axis is also being rotated and you obtain gimbal lock. For example, as you can see in this video, https://www.youtube.com/watch?v=zc8b2Jo7mno the axis are hierarchical. But I don't see the same in UE4. When you rotate in Editor it always rotates around world coordinate system and you cannot obtain a lock. If I can rotate around world (fixed) coordinate system, why shouldn't we always use that and instead use quaternions? Or I miss something?  See all the videos that explain gimbal lock. They always rotate around one axis, while rotating other axis with it too. Why? And at this point, as I cannot obtain the lock, I think quaternions are useless if you rotate around world coordinate system and have 0 problem.


texts: Better way than url-encoded query stings to pass data from PHP to Flash?

texts: For the turn-based browser Flash RPG I'm working on, I'm using url-encoded query stings to pass data from PHP to Flash. Basically, Flash posts a request to PHP, then PHP pulls some data from a MySQL database, does some calculations and echos something like "health=100&mana=50&strength=10" which Flash reads. It seems to work fairly well, but I'm wondering if there is a better way to do it? As I go along, the number of character stats is increasing, and after inventory slots, it will probably be around 100 variables. All that only needs to be pulled from the MySQL database through PHP once at the beginning though, with much smaller queries during gameplay.


texts: Could a Peer-To-Peer network architecture be good for my fighting game

texts:
I am looking forward to developing a 2D spaceship-fighting, brawler game and I have so many ideas about it. I am going to make a single-player component anyway, but the core of this game would certainly be its multiplayer.
For this game, I was inspired by Brawlhalla and its dynamic play-style. In my game, there has to be real-time action features such as attack, dodge, getting hit, killed, so a reliable networking needs to exist. I have thought initially about a client/server architecture, but a peer-to-peer connection would be in my opinion more easily for me to implement.
I have read this article and it proves encouraging for me to go on with this simulation solution.

Let me describe my concept:

A client initializes a room and using sockets, IP, port and the other players would after connect to him. Therefore, there is always a Master Client that handles the new connections and gives signal to other clients about a new existing player. Then, as the game is running, the byte data-packets would stream each player's input, his position, his ship rotation, his ship status and so on, so that each of the other clients could run a perfect simulation of the initial client. In other words, this data packets would trigger all the actions on each client. As network protocol, I am thinking about TCP/IP and should someone be willing explain to me in more practical terms the difference between this and UDP, I would be thankful.

I have even computed how much data it would take to transmit over a second: assuming a byte[256] array that holds all the data at one time multiplied by the number of calls per second (about 32 times) multiplied by the number of clients the data should be broadcasted to (3-4)
results in about 32 kb/s. It might be a dummy result, i might have left a lot of things out, but again, I am ready to learn.

As a note, I do not intend to make at this moment a professional multiplayer system, but rather, I would like to learn more about this programming part of applications and I think this is a very good project idea to enhance my skills.
Of course, I am opened to any advanced tips, solutions, materials and should I add anything else about my concept, please let me know.

How is my theoretical model so far?


texts:
I am trying to create blood effects, where the characters being killed are on an uneven terrain. The simple way is to instantiate a prefab with texture, which uses a plane mesh, on the raycast hit point. But, in this case, this looks quite odd as the terrain has height variance within the bounds of the plane of the blood splatter prefab.

I tried using the projector in Unity, but the issue with using that is that the projector shaders are very simple. In particular, I don't want them to blend into the terrain texture, and wanted to add specularity (to make it look like a liquid).

What is my best option?


texts: Reuse assets across different rendering pipelines

texts:
What is the best way to handle same project with two rendering pipelines that share 99% of the Assets?

We have one really big project for which we've decided to try and use both the URP and HDRP pipelines in Unity. Because of the way our application is setup (it acts more or less like a container) the only differences between the two pipelines from the Assets folder point of view are just 2-3 materials and another 2-3 shaders.

Our scripts are not important most of the code is in dlls and the output it to the correct location automatically.

The best thing that we came up was creating a directory junction between two folders inside of our assets and now the structure looks like this.

HDRP
└───Assets
    └───Custom
    |    |
    |    └─ Materials
    |          Material1.mat
    |          Material1.mat.meta
    |           ...
    └───Shared
         |
         └─ Materials
               Material1.mat
               Material1.mat.meta
               ...
URP
└───Assets
    └───Custom
    |    |
    |    └─ Materials
    |          Material1.mat
    |          Material1.mat.meta
    |           ...
    └───Shared
         |
         └─ Materials
               Material1.mat
               Material1.mat.meta
               ...

The junction was made for the Shared folders, where literally 99% percent or our assets are. The problem with this approach is that we're struggling to override the Shared assets with the custom ones (see my other question). I'd like to know if our approach is wrong and if so why? and what would be better.


texts: How to detect a body between two points on LibGDX

texts:
I've two Vector2 (A and B), i draw a line between them.

Is there a way to check if the line intersect the Box2D CircleShape?
I need to a boolean output


texts: Drawing a texture line between two vectors in XNA WP7

texts:
I want to create a simple graph maker in WP7.

The goal is to draw a texture line between two vectors what the user defines with touch. I already made the rotation, and it is working, but not correctly, because it doesn't calculate the line's texture height, and because of that, there are too many overlapping textures. So it does draw the line, but too many of them.

How could I calculate it correctly?

Here is the code:

public void DrawLine(Vector2 st,Vector2 dest,NodeUnit EdgeParent,NodeUnit EdgeChild)
    {
        float d = Vector2.Distance(st, dest);
        float rotate = (float)(Math.Atan2(st.Y - dest.Y, st.X - dest.X));
        direction = new Vector2(((dest.X - st.X) / (float)d), (dest.Y - st.Y) / (float)d);
        Vector2 _pos = st;
        World.TheHive.Add(new LineHiveMind(linetexture, _pos, rotate, EdgeParent, EdgeChild,new List<LineUnit>()));
        for (int i = 0; i < d; i++)
        {
            World.TheHive.Last()._lines.Add(new LineUnit(linetexture, _pos, rotate, EdgeParent, EdgeChild));
            _pos += direction;

        }
    }

d is for the Distance of the st (Starting node) and dest (Destination node)
rotate is for rotation
direction calculates the direction between the starting and the destination node
_pos is for starting position changing

Thanks for any suggestions/help!


texts: What's the name for the random animations played when character isn't doing anything else?

texts:
In many games, the main characters or enemies usually do some random stuff when idle other than just standing there breathing. For example, they may take a nap or eat some food.

These add nothing to gameplay, but help develop some personality for the characters. I can't find a word to describe them; do these animations have a standard name in the industry?


texts:
I am working on a set of ScriptableObjects that represent base stats for characters in my game. Think Strength, Speed, Intellect, etc. A whole laundry list of em (about 20 stats).
I'd like to later be able to reference these specific stats via an enum. Therefore, the easiest way to store them in the object seemed to initially be a Dictionary<StatType, int>. These then get linked to sliders in a custom editor (which works fine).
However, Unity appears to have no idea how to serialize a Dictionary, so between sessions all my finely tuned values get removed.
I need some sort of workaround for this. Either I need another data structure Unity will serialize (but see below), OR I need to find a way to force Unity to serialize my data some other way.
Requirements for an alternate data structure: Integer values should be able to be read and written through reference to the enum value alone. It should be possible to check whether an enum key has been added to the structure or not. It should not allow duplicate enum keys, but duplicate values are fine. Obviously, Unity should be able to serialize it.


texts: How do you unzip a Texture2D from image or string from txt from a zip file using SharpZipLib

texts: How do you unzip a Texture2D from image or string from a txt file - contained in a zip file - using SharpZipLib or System.IO.Compression?


texts:
I have been learning C++ for long time (but only learning game development for eight days) and I have made a simple game using 2D textures.

I was thinking of starting on 3D game development. I wanted to begin by loading and rendering a 3D model on the program, but I dont know how.

Can anybody tell me if this function could be changed to output 3D model:

GLuint loadTexture( const string &fileName )
{
SDL_Surface *image = IMG_Load( fileName.c_str() );

SDL_DisplayFormatAlpha(image);

unsigned object(0);

glGenTextures(1, &object);

glBindTexture(GL_TEXTURE_2D, object);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image -> w, image -> h, 0, GL_RGBA,
GL_UNSIGNED_BYTE, image -> pixels);

//Free surface
SDL_FreeSurface(image);

Also what format should I use for this? I am using Blender, and I have seen it can export to a variety of formats. I don't know which would be the best for this kind of stuff and for serious game development.


texts: How to remove or disable an extension asset in Unity 2020

texts:
I've been running Unity 2020.1 on Ubuntu 19.04 without any problems for a while now. Today, I installed the VSCode extension asset and now Unity just crashes during startup. I choose my project from Unity Hub, the splash screen and progress bar pops up, and then everything just shuts down.
I've already submitted a crash report but I'd rather just revert the extension entirely so I can get working again. I've tried deleting the files from disk but Unity just downloads them again during startup.
How can I either remove or disable the VSCode extension completely without starting Unity?


texts:
I have a map of the world and I want to place text on top of each country. The text can be anywhere from 0 to 1000 symbols long, and can often be changed.

I'm looking for an algorithm to layout text on top of each country "nicely":

Text ideally should not go outside of the country borders
Placed somewhere near poloygon's centroid
Should be visible when possible

I can change font size, and I can split it into multiple lines.

Currently I'm using naive centroid approach, but it requires lots of manual tweaking, and with changing text it can result in suboptimal placement:

Interactive version of the USA map is available here: http://what-people-google.anvaka.com/ (so that you can see labels placement drawbacks and better understand my use case).

One solution I had in mind was to approximate each country by largest posible axis aligned rectangle that can be embedded inside country shape. But maybe there is a better way to do it?


texts: Separating Axis Theorem fails at certain angles

texts:
I'm currently attempting to add an overlap tester for an axis aligned and orientated bounding box but the solution only seems to work accurately when the OBB's angle is between -10 and +10. As the angle approaches +90 degrees the collision area seems to at first move to the right half of the OBB and then become non existent. Between 90 and 270 I couldn't get an overlap and then when it comes round a full 360 the area registers accurately again.

Any light on this subject would be great. I'm using positive X for 0 degrees increasing CCW.

EDIT: Did a little more research and realized that projecting a vector onto another requires more than just a dot product. Could any one give me a correct version of one of the check axis methods below?

EDIT 2: Actually just a dot product should do I think since the vectors being  projected onto are unit length.

public static bool overlapAABB_OBB(AABB a, OBB o)
    {
        float rads = MathHelper.ToRadians(-o.angle);
        T = Vector2.Subtract(o.position, a.position);
        Ax.X = 1;
        Ax.Y = 0;
        Ay.X = 0;
        Ay.Y = 1;
        Ox.X = (float)Math.Cos(rads);
        Ox.Y = (float)Math.Sin(rads);
        Oy.X = -Ox.Y;
        Oy.Y = Ox.X;
        if (checkAX(a, o) &&
           checkAY(a, o) &&
           checkOX(a, o) &&
           checkOY(a, o))
            return true;
        else
            return false;
    }

    private static bool checkAX(AABB a, OBB o)
    {
        float TAx = Vector2.Dot(T, Ax);
        float WoOxAx = Vector2.Dot(Vector2.Multiply(Ox, o.halfWidth), Ax);
        float HoOyAx = Vector2.Dot(Vector2.Multiply(Oy, o.halfHeight), Ax);
        if (TAx > a.halfWidth + WoOxAx + HoOyAx)
            return false;
        else
            return true;
    }

    private static bool checkAY(AABB a, OBB o)
    {
        float TAy = Vector2.Dot(T, Ay);
        float WoOxAy = Vector2.Dot(Vector2.Multiply(Ox, o.halfWidth), Ay);
        float HoOyAy = Vector2.Dot(Vector2.Multiply(Oy, o.halfHeight), Ay);
        if (TAy > a.halfHeight + WoOxAy + HoOyAy)
            return false;
        else
            return true;
    }

    private static bool checkOX(AABB a, OBB o)
    {
        float TOx = Vector2.Dot(T, Ox);
        float WaAxOx = Vector2.Dot(Vector2.Multiply(Ax, a.halfWidth), Ox);
        float HaAyOx = Vector2.Dot(Vector2.Multiply(Ay, a.halfHeight), Ox);
        if (TOx > o.halfWidth + WaAxOx + HaAyOx)
            return false;
        else
            return true;
    }

    private static bool checkOY(AABB a, OBB o)
    {
        float TOy = Vector2.Dot(T, Oy);
        float WaAxOy = Vector2.Dot(Vector2.Multiply(Ax, a.halfWidth), Oy);
        float HaAyOy = Vector2.Dot(Vector2.Multiply(Ay, a.halfHeight), Oy);
        if (TOy > o.halfHeight + WaAxOy + HaAyOy)
            return false;
        else
            return true;
    }


texts: libGDX sprite image not updating Event Handling InputHandler

texts:
I created a separate inputHandler class implementing InputProcessor. I'm using Event Handling (libgdx github page: https://github.com/libgdx/libgdx/wiki/Event-handling)

public class inputHandler implements InputProcessor {
    private cheetah cheetah;
    private gameWorld myWorld;
    private float cheetahX;

    private float scaleFactorX;
    private float scaleFactorY;

    public inputHandler(gameWorld myWorld, float scaleFactorX,
            float scaleFactorY) {
        this.myWorld = myWorld;
        cheetah = myWorld.getCheetah();
        cheetahX = cheetah.getX();

        int midPointY = myWorld.getMidPointY();

        this.scaleFactorX = scaleFactorX;
        this.scaleFactorY = scaleFactorY;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        System.out.println(cheetahX);
        cheetahX += 5;
        System.out.println(cheetahX);
        return true;
    }

cheetahX is updating in the console, but not on the screen. When I click on the DesktopLauncher window, the console prints cheetahX + 5 properly, but the image of the cheetah sprite remains still.

gameWorld class:

public gameWorld(int midPointY, int gameHeight) {
    currentState = GameState.MENU;
    this.midPointY = midPointY;
    cheetah = new cheetah(33, midPointY - 15, 10, 29);
}

public void update(float delta) {
    runTime += delta;
}

gameScreen class:

@Override
public void render(float delta) {
    // TODO Auto-generated method stub
    runTime += delta;
    world.update(delta);
    renderer.render(delta, runTime);
}

thanks in advance!


texts: Simulated 3D hit point from surface normal

texts: Here is an illustration describing what I'm trying to do...


texts: Identify a selected prefab rather than all of them

texts:
I am trying to play a particle effect when an enemy is killed but it seems to play on a randomly selected one rather than the one that was hit. However the enemy that was hit still disappears and still add points to the score.

At the moment I have three scripts to carry this out (All have been shortened so I'm only showing the relevant code):

One which is attached to boxes that are thrown at enemies that detects if they have collided with an enemy prefab.

void OnCollisionEnter (Collision theCollision) {

        if (canProjectileKill == true) {
            // If the projectile hits any game object with the tag "Enemy" or "EnemyContainer".
            if (theCollision.gameObject.tag == "Enemy") {
                GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().ProjectileHasHitEnemy();
                // Destroy the projectile itself.
                Destroy (gameObject);
                // Destroy the game object that the projectile has collided with (E.g. the enemy).
                Destroy (theCollision.gameObject);
                GameObject.Find("Manager").GetComponent<projectileSpawner>().deleteProjectile();
            }
        }
    }

Another that is attached to the enemy prefabs which detects if they have been hit by a box.

void OnCollisionEnter (Collision theCollision) {
        if(theCollision.gameObject.tag == "Projectile") {
            GameObject.Find("EnemyExplosion").GetComponent<enemyDeath>().EnemyHasBeenHit();
        }
    }

I then run an if statement asking if both the box has hit the enemy prefab AND if the enemy prefab has been hit by the box in an attempt to identify a single prefab rather than all of them. However this still doesn't work.

    public bool HasProjectileHitEnemy;
    public bool HasEnemyBeenHitByProjectile;

    void Start () {
        gameObject.particleSystem.Stop();
        HasProjectileHitEnemy = false;
        HasEnemyBeenHitByProjectile = false;
    }

    public void ProjectileHasHitEnemy () {
        // From projectile.
        HasProjectileHitEnemy = true;
    }

    public void EnemyHasBeenHit () {
        // From enemy.
        HasEnemyBeenHitByProjectile = true;
        PlayParticleSystem();
    }

    public void PlayParticleSystem () {
        if (HasEnemyBeenHitByProjectile == true && HasProjectileHitEnemy == true) {
            gameObject.particleSystem.Play();
            HasProjectileHitEnemy = false;
            HasEnemyBeenHitByProjectile = false;
        }
    }
}

I am aware this is a long question but I have been stuck on this for over a week, so any help would be much appreciated. Thank you :)