texts:
I found this script on a tutorial that I want to implement into my game, but I first want to understand what it does and how it does it. The script is attached to a Joystick UI, which has the inner ring/button of the joystick as its child. The script makes the inner button of the joystick move within a certain confine, when the player uses the joystick. "joystickButton" is the child object.
public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{

public Image joystickButton;

public Vector3 inputDirection;

void Start()
{
    inputDirection = Vector3.zero;
}

public void OnDrag(PointerEventData drag)
{
    Vector2 position = Vector2.zero;

    RectTransformUtility.ScreenPointToLocalPointInRectangle (joystickButton.rectTransform, drag.position, drag.pressEventCamera, out position);

    position.x = (position.x / joystickButton.rectTransform.sizeDelta.x);
    position.y = (position.y / joystickButton.rectTransform.sizeDelta.y);

    float x = position.x * 2;
    float y = position.y * 2;

    inputDirection = new Vector3(x, y, 0);
    inputDirection = (inputDirection.magnitude > 1) ? inputDirection.normalized : inputDirection;

    joystickButton.rectTransform.anchoredPosition = new Vector3(inputDirection.x * (joystickButton.rectTransform.sizeDelta.x / 3), inputDirection.y * (joystickButton.rectTransform.sizeDelta.y) / 3);
}

public void OnPointerDown(PointerEventData drag)
{

    OnDrag(drag);
}

public void OnPointerUp(PointerEventData release)
{

    inputDirection = Vector3.zero;
    joystickButton.rectTransform.anchoredPosition = Vector3.zero;
}

}
I did some research and some tests, and from what I understand, if I tap a point within the Joystick UI's RectTransform, the point I tap, "drag", gets converted to a position in the RectTransform of joystickButton. The position is then converted to a vector, inputDirection, which represents the direction and location of my tap. The vector is then normalized, and the joystickButton is moved to
(inputDirection.x * (joystickButton.rectTransform.sizeDelta.x / 3), inputDirection.y * (joystickButton.rectTransform.sizeDelta.y) / 3),
where the vector is pointing to the direction of my tap, and has a magnitude that is 1/3 the length of the side of joystickButton's RectTransform, since all the anchors are centered, and the RectTransform is a square.
What I don't get is why I need these lines:
RectTransformUtility.ScreenPointToLocalPointInRectangle (joystickButton.rectTransform, drag.position, drag.pressEventCamera, out position);

and
float x = position.x * 2;
float y = position.y * 2;

Is there any purpose to these lines?
Converting the 1st one to
position = drag.position

and the 2nd one to
float x = position.x;
float y = position.y;

doesn't seem to mess anything up.
Also, I didn't notice at first, but not dividing on by sizeDelta on these lines
position.x = (position.x / joystickButton.rectTransform.sizeDelta.x);
position.y = (position.y / joystickButton.rectTransform.sizeDelta.y);

does change the result slightly, so if anyone can tell me what function dividing the values does, it would be greatly appreciated.


texts: How can I generate vertex data from an SVG?

texts:
I am trying out the Phaser game engine, and am interested in making a vector graphics game (simple black and white like Asteroids), but I want to use vector graphics instead of raster PNGs.

I was looking at this example, which looks like what I want to do...

Where I am stuck is, say I draw a simple Asteroids style ship in Illustrator, consisting of 3 connected lines.  How do I export that data into an array of vertices that would work with the setPolygon() method in Phaser/Box2d?


texts: Why do unidentified items seem to solely exist in roguelikes?

texts: Playing a variety of games I noticed that some concepts are "trapped" in the realm of roguelikes. One of the most intriguing game-play elements in roguelikes is the unidentified item. The unidentified item can be used at any time adding another layer of randomness and chance to the game-play. I think the reason this element cannot co-exist with a saving mechanic is that you could save, use the item and then load if you are unhappy with the results. I am still puzzled if this mechanic is overlooked and it could possibly be successfully incorporated into some modern games? If you do know of examples where it is being used, please share.


texts:
I have a tick-based Multiplayer-RTS game: Client sends action to server at Frame n which will be broadcasted to all clients and executed at Frame n+x (x depends on network latency of slowest player)

I'm unsure how to hide this latency in GUI dialogs. E.g. a value that is adjustable with a slider between 0 and 100. The current solution simply fills a "virtual" value with the actual value at game start and always operates on that value. It is highly unlikely that a change command for this does not get executed (TCP, unconditional change execution) but it is possible (packet sent and ignored during pause)

I also wanted to keep that value local to the dialog and not store it somewhere else. Start idea: Get the current value on dialog open and use this while the dialog is open. Problems: Maybe the value was changed before (packet sent, but not executed) in which case the change does not get displayed. An idea I have is storing the last value I got and update the slider if that value has changed. Maybe only when the sliders position itself did not change (by the user). However then after the update it will detect that change and change it again which leads to a change of twice the amount requested. I could also update the "last value" when the packet is sent but that will cause the (time-based) update to change it back till the actual change is made which might even result in a loop of back-and-forth changes. How can I keep the GUI and game in sync but allow visual changes? Seems I'm missing a little piece here...

Another part where this is even worse is with other kinds of dialogs. E.g. an ordering dialog (put some entities in a specific order) or a number input that is used to request producing the specified amount, hence the game may also decrease this, not only the packet. I could not find any guides or solution besides "use inter/extrapolation" which is not applicable here. How do others do this?

Edit: Maybe a little example for the strategy I though off with its flaws:
A) OK

Value=4
Open Dialog -> Show Value=4
User Changes Value to 6 (Slider position change)-> Sent to server
Server sends "6" -> Slider changes to "6" (no change as it already is)

B) OK

Same as A) but dialog closed before receiving from server
Dialog reopened -> Show Value=4
Server sends "6" -> Slider changes to "6"

C)

Value=4
Open Dialog -> Show Value=4
User Changes Value to 6 (Slider position change)-> Sent to server
User Changes Value to 7 -> Sent to server
Server sends "6" -> Slider changes to 6 BAD
Server sends "7" -> Slider changes to 7 => OK, but strange and may cause feedback loops

D)

Value=4, change to 6 requested
Open Dialog -> Show Value=4 (6 was stored in the old dialog)
User Changes Value to 7 -> Sent to server
Server sends "6" -> Slider changes to 6 BAD
Server sends "7" -> Slider changes to 7 => OK, but strange and may cause feedback loops

So on one hand I only want to show visual values (and store them between dialogs) but on the other hand I want to keep them in sync with the actual value. So only solution here seems to be to persistently store the visual value and make sure, each update will eventually be executed. But I'm still clueless what to do with values that can be changed by the came (e.g. production orders that decrease once they are processed)


texts: How to determine if and when a point and triangle moving uniformly will collide?

texts:
TLDR; I just learned this problem can be simplified to:  How to determine the time at which a uniformly moving point will intersect with a stationary triangle?  Also, how to figure out the time when the point will exit the triangle?

I have a player with a triangular line of sight ("field of vision" would be more a accurate term here).  I also have an NPC, represented by a point.  Currently I have the server update the client about both their positions only when one of them changes speed or direction of movement.

Without a limited field of vision, I was able to solve this.  How I intend to solve this new problem is as follows:

Each time either the player or NPC changes speed or direction (speed is a boolean at the moment, 1 or 0, and will probably remain that way), figure out if a line drawn from the point NPC to the edge of the game "room" at the angle of it's current direction, is within a triangle consisting of one point at the player's current position, and the other two points at the location they would be if the player were to reach the edge of the room moving at their current angle.
If the above is false, we can ignore the following steps because it means the NPC can't enter the vision field.  But if true, continue.
Figure out at what time the NPC will intersect the player's field of vision.  This, I do not know how to do, but I expect there is some formula I can use instead of checking every tick.
But once I do have this formula, I will use it's return value to set a timer that, when it goes off, will have the server update the client and tell it the location of the NPC.
Then I will have to also figure out at what time the NPC will exit the field of vision, and tell the client to delete or inactivate that NPC.

Does anyone know what mathematical formula I'm looking for?  I need to figure out when a moving point will intersect a moving triangle, when they are both moving uniformly (not changing direction or speed).  Also, the point in time when the point will exit the triangle.


texts: Abstracting multiple math libraries with C++

texts:
I would like to create some level of abstraction above math in my code. I mean I don't want to be dependant on the implementation of math operations or even on class names, which are provided by some math library. I will show you a simple example.

Let's assume that we have 2 math libraries. Let's consider 3D-vector classes:

Library A has 3D-vector class as "Vector3D" and its method "Subtract".

Library B has 3D-vector class as "vector3" and its method "subtr".

Now I want to be able to swtich between these 2 different implementations, but without changing any line of code. For, instance I would like to have it like this:

My 3D-vector class name will be "vec3" and its method "sub". But behind "vec3" and "sub" it can be implementation from library A or library B, depending on what I choose with 1 line of code in the beginning of program or even on compilation stage.

In other words it should look like a plugable system for math libraries.

I think it's about programming patterns here right? It look like delegation or factory. Could make clear for me how to implement this approach and is it worth it?


texts: Unreal Engine Ubuntu: Failed to import video, unknown file extension

texts: I've been reading tutorials and guides on getting video file playback in Unreal. I have media player materials created and textures. I'm having issues importing video files to Content/Movies directory. When I use the import manager the files don't show. Drag and drop says its an unknown file extension for MP4, MWV, and other formats I tried like AVI even though I know AVI is not supported. So I wonder if maybe I'm missing a plugin for Unreal 4.8 / 4.9 in Linux?


texts: Render text and still have it interractive with minimum effort with hit-testing?

texts:
The background of the situation:

I need to render text. Text will be moving aroud the screen and
user will have ability to interact with it by erasing with a finger,
shifting the order of the words, deleting letters and so on.
Text will be in many different languages.
Kering and other typing tricks should be implemented when
rendering.

So the problem for me:

I don't know the most efficient way to render all the text AND at the same time to have information about the location of each and every letter on the screen, plus each letter should know the word it belongs.

Now, if I make a big class of strings, where each letter is a child of each word, and words are the children of sentences, then interaction part seems trivial to implement, but rendering becomes a problem since

either I render each letter to the pipeline individually and store it's location in screen coordinates.
or I prepare one big string  by gathering letters from all the above mentioned classes and render it in one run, but I loose the ability to store the coordinates of each letter in the screen coodrinates.

Is there a way to have both :) Fast rendering in one string and coodinates of each letter stored?


texts: Pre Computing shadows, advantages/disadvantages?

texts:
Today I was looking at a still frame of a game, and noticed that all of the shadows were dynamic (created per frame). As we know, shadows can be quite expensive.
I was wondering why shadows could not be simply mapped at run time for non moving objects, and then only do dynamic shadows for players, vehicles, etc.
What are the advantages/disadvantages of doing this?


texts:
I'm currently trying to teach myself OpenGL... and quickly discovering that the Immediate Mode taught in old OpenGL tutorials is basically obsolete... which leads me to VBO's... which I kind of get but would like to start learning them in context.

What is the workflow involved in taking a 3D object from Maya or 3DS Max and converting it to something that can be turned into a VBO?

On that token, do these export workflows also deal with materials and textures, or is that handled in an entirely different manner?


texts: Windows 10 GPU Engine Performance Counters - Phys / Eng Meaning

texts:
For performance tracing of intermittent degredation in performance I wanted to use the Performance Counters available in Windows 10 1809 under GPU Engine -> Utilization percentage. This particular laptop has NVIDIA GeForce GTX 1050 with 4 GB VRAM + 16GB shared memory.

The instance names look like this:

pid_1388_luid_0x00000000_0x00011372_phys_0_eng_8_engtype_Compute_1
pid_912_luid_0x00000000_0x00010F5C_phys_0_eng_2_engtype_Copy

While I know pid_xxxx is the process identifier, what I am trying to work out the meanings of remaning components.

1) luid_xxxx_xxx

In my case all instances start with luid_0x00000000 and have 3 different endings:

0x00010F5C
0x0001134D
0x00011372

2) Next is phys_0, I assume this is first physical GPU, but I want to be able to programatically translate it to GPU adapater name.

3) Eng_x, on my machine this ranges from 0-12

4) Eng_type have the following. While mostly self explanatory, is the difference between Compute_0 and Computer_1 different cores on the GPU

3D
Compute_0
Compute_1
Copy
GDI
Render
Graphics
LegacyOverlay
Security
VideoDecode
VideoEncode
VideoProcessing
VR


texts: Phaser Always Fix Camera Position to Sprite

texts:
I am developing a cross-platform overhead game using Phaser.

Is there a way to always fix the position of a camera to a sprite? The following function works great, but I want the camera to always be centered on the sprite - even when the sprite is nearing the edge of the tilemap.

this.game.camera.follow(this);

The reason I would like this capability is because I am developing a mobile game, and the player sprite manages to get in the way of crucial UI elements. This could be fixed by providing a constant camera on the sprite. Areas without tiles can be filled with a black background.

Here is my problem visualized. As you can see, when nearing the edge of the tilemap, the sprite is no longer centered and it is in the way of my joystick. Instead, I would like the sprite to be centered and the camera to display a black background past the tilemap when it gets near edges.

Thank you in advance,

Christopher


texts:
I wanted bullets to bounce when they hit walls. However when colliding with a wall, they just jitter about on them. I didn't want to create a new physics material as I want to keep the ball moving at a constant speed and to have them destroy themselves after they have bounced once. Thus, I wrote everything in Code.
The constraints for the bullet rigidbody's freezing position is the Y axis while the freezing rotation is X, Y, and Z axis.
I also wondered if the initial position the instantiated bullet also had something to do with the speed the bullet travels:
GameObject bulletObject = Instantiate(bulletPrefab);
bulletObject.transform.position = transform.position + (transform.forward * -1);

Here's the minimum reproducible code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class bulletMovement : MonoBehaviour
{
    private Rigidbody bulletRB;
    private Vector3 lastVelocity, initialVelocity;
    public float bulletSpeed = 10f;
    private int bounceCount;
    // Start is called before the first frame update
    private void Start()
    {
        bulletRB = GetComponent<Rigidbody>();
        bounceCount = 0;
        bulletRB.AddForce((transform.forward* -1) * bulletSpeed);
    }

    void Update()
    {
        lastVelocity = bulletRB.velocity;
    }

    // Update is called once per frame

    private void OnCollisionEnter(Collision col)
    {
        if (col.collider.tag == "Walls")
        {
            bounceCount += 1;
            if (bounceCount < 2)
            {
                Bounce(col.contacts[0].normal);
            }
            else
            {
                Destroy(gameObject);
            }
        }
    }

    private void Bounce(Vector3 normal)
    {
        var speed = lastVelocity.magnitude;
        var direction = Vector3.Reflect(lastVelocity.normalized, normal);

        Debug.Log("Out Direction: " + direction);
        bulletRB.velocity = direction * Mathf.Max(speed, bulletSpeed);
    }
}

lastVelocity = bulletRB.velocity; is required to be in Update or else the bullet won't move at all.


texts: How can I offset a direction when raycasting?

texts:
I'm trying to figure out how I can best offset a direction when raycasting.

So let's say I have an object and I want to cast a ray from my mouse position to said object, that's easily done with (for example):

// "obj" being the transform of the object I'm raycasting to.
Vector2 mPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 dir = (Vector2)obj.position - mPosition;
Debug.DrawRay(mPosition, dir, Color.green);

But what if I want the direction to always be slightly offset to the right of the object from the mouse position? And I mean not just to the right of the object itself, but to the right from where the mouse is.

I hope I'm making any sense. Here are some pictures to try and make it a little more clear:
(Pretend the line is the ray and the circle is the object)

I want to offset the ray so that when my mouse is under the circle, it goes to the right of it, like this:

However, when I move my mouse to the left of the object, the ray should instead go like this:

Meaning the ray will always cast to the right of the object from where the mouse is.

The reason I want to do this is because I'm trying to raycast to the corners of objects, but also see what's past them:

I need to use offset rays to just barely miss the corners and allow them to continue on and see if there's a wall behind them like on the picture above. I'm offsetting my rays in the picture above, but the way I'm doing it isn't the best and I'm trying to find the proper way of doing it.


texts: I'm developing a game using fixed time step, and so far I haven't been using XNA's GameTime class in my code.  What uses does the class have, and should I definitely use it in my game, or can I ignore it?


texts: How can I change the Value in HSV color via scripting?

texts:
I have a glowing object (point light attached to a ball with a default shader with the emission property) in my scene and I've added a script to make the point light flicker.
The script randomly changes the intensity of the point light to make it flicker.
Since I'm using an emission shader, the ball can also be seen without light.
I'm using HDR values in my emission shader and by changing the Value in the HSV Color picker I can change the color of the ball to black.
I need help in linking the value of the HSV color on the emission shader of the ball to the intensity of the point light.
Any help would be useful! Thanks!


texts:
In my game more than 600 images and 200 sounds. I'm try organize effective images and sounds manager for fast access. This is a good approach?

public class Images
{
    public static var image_1:BitmapData;
    public static const image_1_class:Class;

    public static var items_icons:Vector<BitmapData>;
    public static const item_1_class:Class;
    public static const item_2_class:Class;

    ...
}

// initialization
Images.image_1 = new Images.image_1_class().bitmapData;
Images.items_icons[0] = new Images.item_1_class().bitmapData;
Images.items_icons[1] = new Images.item_2_class().bitmapData;

// using
new Button().setTexture(Images.button_close);
sounds.playRandom(Sounds.gnome_hit);


texts: Unity move Vector3 position with transform

texts:
How can I move a new Vector3 position with a Transform? Like the transform is the parent the vector.

Example if I want to push the x position for example by 10 value and I rotate the transform its push in world coordinate but I want to push by the rotation too.

    void Update () {
    temp = transform.Find("Transform").position;
    temp = new Vector3(temp.x + 10.0f, temp.y, temp.z);

    Debug.DrawLine(transform.Find("Transform").position, temp);
}


texts: How to deal with Character body parts from Design to Cocos2d

texts:
I'm trying to figure out the pattern the game developers use together with game designers:

See the picture below with the independent parts:

Questions:

1) Should I create different image parts from different body parts or keep frame by frame animaton? (I know both can be used, but I'm trying to figure what is commonly used in the industry)

2) If I'm going to generate different image parts from different body parts (which is I thing is more logical) how would I export that to Cocos2d (Vector or Bitmap)?


texts:
Not able to implement Perlin Noise for 1D Random Terrain Generation. I've tried everywhere and I cannot find anything useful, sure I sort of understand Perlin Noise but everytime I try it nothing works. I'm using LibGDX in Java if that helps, thanks.

Here is the code for P.N.

static float Noise(int x) {
    x = (x << 13) ^ x;
    return (float) (1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & Integer.MAX_VALUE) / 1073741824f);

}

public static float PerlinNoise1D(float x, float persistence, int octaves) {
    float total = 0;
    float p = persistence;
    int n = octaves - 1;

    for (int i = 0; i <= n; i++) {

        float frequency = (float) Math.pow(2, i);
        double amplitude = Math.pow(p, i);
        total += InterpolatedNoise(x * frequency) * amplitude;
    }

    return (int) total;

}

private static float InterpolatedNoise(float x) {
    int integer_X = (int) x;
    float fractional_X = x - integer_X;

    float v1 = SmoothNoise1D(integer_X);
    float v2 = SmoothNoise1D(integer_X + 1);

    return CosineInterpolate(v1, v2, fractional_X);

}

public static float CosineInterpolate(float a, float b, float x) {
    float ft = (float) (x * Math.PI);
    float f = (float) ((1 - Math.cos(ft)) * 0.5);

    return a * (1 - f) + b * f;
}

public static float SmoothNoise1D(int x) {
    return Noise(x) / 2 + Noise(x - 1) / 4 + Noise(x + 1) / 4;
}

and here is the code for the for loop used to render the tiles (assuming my tiles are 32px x 32px)

for (int i = 0; i < Gdx.graphics.getWidth(); i++) {
    float y = PerlinNoise1D(i, 5f, 3);
    for (int j = (int) (y); j < Gdx.graphics.getHeight(); j++) {
        hudBatch.begin();
        hudBatch.draw(hp, i, j);
        hudBatch.end();
        j+=31;
    }
    i+=31;
}

P.S I'm sort of trying to create a terraria-like game.


texts: Unity3D/Blender: Bounding box rotated on import

texts: For some reason my bounding box is always tilted when i import to unity. I've checked for loose geometry and everything but there's nothing.


texts: How to achieve best performance in DirectX 9.0 while rendering on multiple monitors?

texts:
I have read this article, and I am making use of some pixel shaders to achieve some effects. At most four shader effects can be applied at same time. What are the best practices to achieve best performance with DirectX 9.0.

I read somewhere that DirectX 11 provides support for parallel rendering, but I am not able to get any working sample for DirectX 11.0.

How can I boost the performance of my application? Are there any best practices for rendering different things on multiple monitors at the same time?


texts:
I'm having an issue with a simple HLSL pixel shader. As a start to writing a lighting engine, I created a point light texture that looks like this. The texture itself is a white -> transparent gradient, drawn here on a black background for visibility.

As a simple test, I wrote a shader to sample from that light texture. Here's the HLSL code.

texture2D pointLightTexture;

sampler pointLightSampler = sampler_state
{
    Texture = <pointLightTexture>;
};

struct VertexShaderOutput
{
    float4 Color : COLOR0;
    float4 Position : SV_POSITION0;
    float2 TexCoords : TEXCOORD0;
};

float4 PointLightFunction(VertexShaderOutput input) : COLOR0
{
    return tex2D(pointLightSampler, input.TexCoords);
}

technique PointLightTechnique
{
    pass Pass0
    {
        PixelShader = compile ps_4_0 PointLightFunction();
    }
};

But the resulting "light" is just a pure white rectangle.

So my basic question is, why is this texture sampling not working? I've already verified that 1) the texture is correct (I can draw the texture in isolation and it looks fine) and 2) the texture coordinates within the shader are correct (i.e. they properly span 0 to 1 within the bounds of that white square). In the past, I've run into issues when trying to use multiple samplers within one shader, but as you can see, this shader just has one.

More generally, I've been getting extremely frustrating using HLSL shaders. It seems very difficult to do even basic tasks, even when I know my logic is correct (i.e. draw a square and sample from the texture appropriately). Feels like the shader compiler optimizes the code so aggressively that most shaders just don't work. Further more, it seems silly that I should have to 1) store the point light texture and 2) create a sampler specifically using that texture, rather than just being able to call pointLightTexture.Sample(pointLightSampler, input.TexCoords);.

Is there something fundamentally I'm missing? Is there a way to disable HLSL's crazy optimizations? Is it an issue using Monogame? It seems crazy to me that I constantly have to fight against these shaders.


texts: 2D bouncing ball simulation - angular velocity

texts:
How does angular velocity of a ball affects it's speed after a bounce? I'm trying to simulate 2D bouncing ball physics. I've found a nice solution how to calculate ball's velocity after a bounce:

mVelocity.x *= 1 + mi * (e - 1);
mVelocity.y *= -e;

where mVelocity.x is a component of ball's velocity parallel to the "surface" of a bounce, mi is coefficient of friction, e<=1 representsthe energy loss during the impact.

It's looks quite realistic, however I'd like to calculate angular velocity as well - and I assume it's also affecting how the ball actually bounces. I tried to achieve it using matrix found on wolfram site - http://demonstrations.wolfram.com/BouncingASuperball/ (it's in the bottom of the page), but its implementation doesn't look realistic at all, ball is acting very wierdly. How can I calculate it?


texts: How to randomly spawn objects off-screen close to the player?

texts:
I am making a zombie game. I want to have it so zombies randomly spawn. My code for this is:

instance_create(
  obj_player.x + irandom_range(-300, 300),
  obj_player.y + irandom_range(-300, 300),
  obj_zom_1 )

The problem with this is that zombies will sometimes spawn really close to the player. I want to have it so zombies spawn randomly but to NOT spawn on the visible screen, because seeing zombies materialize out of nowhere looks silly.

How would I do that?


texts: XNA Drawing Glitches (maybe Viewfrustum related?)

texts:
I'm drawing a simple Voxel world.  When I naively render all the vertices, things look fine.  But when I change my code to include a ViewFrustum check, I start getting strange visual glitches like this:

glitch http://www.phillipwei.com/game/glitch.png

The large square block is meant to be there; the strange triangles on the bottom left are not.  These glitches appear all over the screen, and intermittently appear/vanish as I move my camera around.  The draw code looks something like this:

basicEffect.World = Matrix.Identity;
basicEffect.View = Matrix.CreateLookAt(
    camera.Position,
    camera.Position + camera.GetForward(),
    camera.GetUp()
);
basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(
    camera.FieldOfView,
    camera.AspectRatio,
    1.0f,
    1000.0f
);

BoundingFrustum viewFrustum = new BoundingFrustum(basicEffect.View * basicEffect.Projection);

List<VertexPositionTexture> vertices = new List<VertexPositionTexture>();
foreach (Voxel voxel in voxelWorld.GetAllVoxels())
{
    if (viewFrustum.Intersects(voxel.Cube.BoundingBox))
    {
        vertices.AddRange(voxel.Cube.GetVertices());
    }
}

if (vertices.Count != 0)
{
    foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
    {
        pass.Apply();
        using (VertexBuffer buffer = new VertexBuffer(
            graphicsDevice,
            VertexPositionTexture.VertexDeclaration,
            vertices.Count,
            BufferUsage.WriteOnly))
        {
            buffer.SetData(vertices.ToArray());
            graphicsDevice.SetVertexBuffer(buffer);
        }
        graphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, vertices.Count);
    }
}

So if I remove the viewFrustum.Intersects() check everything is fine.  It seems unlikely to me that the viewFrustum check itself is causing the error, but I can't figure out where the problem is coming from.  Any suggestions?


texts: Reconstructing mesh from topological skeleton?

texts:
I have a topological skeleton of a 3d maze-like level (think Descent[I]/II). It looks like a tree where each node is a vertex in 3d-space.

If it were on a 2d plain, I would "simply" use this to offset it and reconstruct the polygon. However, it's not a 2d skeleton and I am interested in 3d mesh outward offsetting it in 3d space.

What I tried so far is offsetting outward as if it were in 2d space and then extruding the flat shape into a 3d-object. This however does not work where two edges in the skeleton are close to one another as they intersect after this process.

Is there an algorithm or tool that accomplishes this?

I am trying to do the opposite of this I believe:

skeletonization

Please notice that this is a graph with simple cycles, in my specific case it's a tree.

Starting from a skeleton and getting a rough mesh without buggy intersections.

This is an example of what it would look like after being offset outwards (inflated). Minus the intersections of course.


texts: How to make an illusion where the contents of a 3D shape change based on which face you look through?

texts:
I remember coming across a Unity 3D tutorial where there was a technique where the contents of a 3D shape change based on which face you are looking at, similar to this screenshot from Antichamber:

What is this techique called? And how do I implement it into a Unity 3D project?
Thanks in advance.


texts:
I made a game using one of the Unity tutorials on their site and now would like to run on my phone (LG P500). But when I try to run it on the device, it says:

  Failure to initialize: Your hardware does not support this application, sorry!

What can I do in this case?


texts: Structure examples for web-based chat for web-based game

texts:
What would be the best tools to use to create a web based chat/messaging system ?
for client we have :
Browser (any JS solution - preferably without using flash like in jsocket)

for server we have :
PHP / Python / (node.js not sure of this one yet)
scalable MySQL structure
scalable MongoDB clusters
scalable redis server
couple of memcache servers (128GB ram each)
bunch of servers with routers (socket base load balancers stage-4)
zero -MQ and/or rabbitMQ

we will have guild chat, area chat (within Xkm) / territory chat / PM
we have more than 1M players, 20K concurrent/online players who will be chatting in groups
every group will have around 100-2k players depending on geo-location
clients will have mobile apps (android and iphone) and will receive push notifications if they select to (and push notifications for PMs as well)

my question is what would be the best combination of client-server technologies to use ?

thanks


texts:
I just got a Razer 14 Inch 4k with a GTX 1060 and am having some blurry rendering in unity. Also the cursor is tiny... Here is a screen shot:

As you can see, the rendering is really blurry. I came from a mac and did not expect unity to look worse after switching to a computer with a great screen res and graphics card...

Please help!

EDIT:

I am still getting jagged shadows but now I seem to be able to fix it with changing shadow distance in Quality Project Settings:

But then the shadow disappears really quick if i have low shadow distance...


texts:
Say I'm making this big game in C# with XNA.

What options do I have to include a scripting feature to my code base?


texts: If there is possibility to use two or more activities in gdx?

texts: I wanted to open another activity or show native android dialog from AndroidLauncher in gdx. But when I add MyActivity and MyDialog classes, there is an error "Error: The number of method references cannot exceed 64K". But when I delete this classes everything works fine. Is there a way to open another activity in LibGDX game?


texts: Cannot run quake 3 engine compiled from source code

texts:
Recently I tried to compile and run the source code of Quake 3 engine. I basically followed this article. However it doesn't work for me.

I am using Visual Studio 2010 on Windows 7, with June 2010 DirectX SDK (I doubt if it is necessary). Here is how I did:

Install the original version of Quake 3 Arena to "D:\Quake III Arena", and update to 1.32
Download and extract the source code
Open quake3.sln in "code" folder. Visual Studio upgraded it to 2010 format.
Build all the 8 projects in Debug mode (in some order). I checked that every project had been built successfully
In the properties of quake3 project, in Debugging page, I changed "Working Directory" to "$(TargetDir)" and "Command Arguments" to "+set fs_cdpath "D:\Quake III Arena""
Set quake3 as the Startup Project and press F5

The game started and could correctly recognize the game folder and parse some options, such as screen resolution. However an exception window popped out before I can see the game main menu, saying "Unhandled exception at 0x053e9938 in quake3.exe: 0xC0000005: Access violation."

I tried to start the game from command line, but it had the same problem.

I followed the code and found that the exception was generated in int VM_CallCompiled(vm_t *vm, int *args), when executing call entryPoint in the __asm block, located in line 1148 of vm_x86.c. Since it's assembler code, I don't know how to debug it.

I don't know if anyone here knows about this problem. Could anyone provide some help on this? Thanks gratefully.


texts:
I understand that typical path algorithms are based on nodes in a graph (not tiled nodes or whatever), but i can't get my head around to find an idea how to implement a path finding algorithm for a grid with endless possibilities (my mapdata is based on vectors so for example an rectangle could be the 1000th of one unit wide but still an obstacle).
I basically have a map with 1 or more fixed sized units and need them to travel the shortest path through a field of rectangles and circles which are not passable.
The question is is there a way to use normal pathfinding algorithms with that mapsceme (how do i calculate the nodes then?) or do i have to use a special one?


texts: How can I stop and resume a coroutine over and over again?

texts: I want a coroutine to enter by default and then to stop when any input is given to it but then after some code to return again as active. So basically to start and stop a coroutine as many times as it's needed.


texts: How to load Preference file in Libgdx asynchronously using Asset manager?

texts: The Preference and AssetManager documentations don't mention this.


texts: Pygame surface rotation, rect rotation or sprite rotation?

texts:
i seem to have a conceptual misunderstanding of the surface and rect object in pygame.

I currently observe these objects this way:

Surface

Just the loaded image

rect

the 'hard' representation of the ingame object (sprite). Used for simplifying object moment and collision detection

sprite

rect and surface grouped together

What i want to do is rotate my sprite. The only available method i found for rotation is  pygame.transform.rotate.

How do i rotate the rectangle, or even better, the whole sprite?

Below is the image of how i visualize this problem.


texts: Class for each specific item in an RPG, or use a factory?

texts:
I had a question regarding the best way to have items in my RPG game.

Currently I have a class structure in which everything inherits from GameObject. Item inherits GameObject. Armour Inherits Item. Helmet inherits Armour. Etc.

I am wondering whether I should have a class for each specific piece of armour, weapon, item, etc. in the game, or whether I should have generic "Helmet", "Shield" etc. classes and then use a factory instead to fill in the constructor arguments. I am unsure of whether the number of classes will become too much and if this is bad.

Classes:

Item* firstHelmet = new LeatherHelmet();
Item* otherHelmet = new SteelHelmet();

Factory:

Item* firstHelmet = Armour::Create(ArmourType.Helmet, Tier.Leather);
Item* secondHelmet = Armour::Create(ArmourType.Helmet, Tier.Steel);

The first example will result in a large number of classes. However, the second example is going to result in a lot of if statements or switch cases to query the type and tier of armour being created and then setting the appropriate variables.

Which is best, or is there another better solution I am missing?


texts:
I'm fairly new to programming in a 3d world.

I'm trying to create a canvas where all the objects are drawn in order of furthest-to-closest and from bottom to top - so they don't overlap each other, but there are problems.

As you can see, some of the objects are overlapping each other. None of the objects in the screen will be moving so I was wondering: is there an algorithm available to sort the objects in the correct order?
At the moment I have them sorting in the Z axis ascending, then X descending and Y descending.


texts: As described in this article you can define render states such as ZFunc inside of the HLSL shader. You can also set these from application code. If you set the same state (e.g. ZFunc) in both application and HLSL, which one wins and gets used? Does it always use application over HLSL?


texts: GameMaker: how to let the game run as fast as it is able to?

texts:
I am making a game/simulator where I want the game to, upon command, run as fast as the computer can handle, that is to say, if the game can run at 60 fps, don't run at 30 fps.

What should I do to make the game do that and would this even make sense?

(Note: when I looked at the built-in variable fps, I often see the value to be higher than the room speed I set, so I thought that maybe I can allow the game to run faster than the room speed initially set.)


texts: Best memory allocation strategy for iOS?

texts:
I'm debating myself about memory allocation on iOS. I write most of my code in C++ and I really like using ObjectPools, FreeLists, etc. In order to pre-allocate a lot of the stuff that I'll be constantly "alloc/dealloc" during the course of my game, ( like particles, game entities, etc ).

Still on iOS, it's not like we are developing for a console like PSP, where I can know for fact that I'll get a fixed amount of memory. iOS , will issue "memory warnings" when the system needs memory.

Does anyone have some suggestions about this ? Is it too serious since the new iPod touch/iPhone 4 are carrying more RAM ? or it's still a big concern?


texts:
I can export the landscape of UE4 (File -> Export Selected -> .obj / .fbx) and load a landscape, for example, in Maya. But how is the modified landscape loaded back into UE4? Otherwise, how to import terrain to UE4? Thank.

P.S.: Any format and any editor are interested.


texts:
I'm starting up on OpenGL, and want to write a well structured and expandable, yet relatively simple 3D graphics engine for fun and personal knowledge. I'm looking for information concerning the best practices and design patterns related to this sort of code.

Specifically, I'm having issues deciding how classes should be organized, how to divide responsibilities, etc. Right now, I'm at the point where everything is done in the rendering method!

Can anyone give me some advice? How are the responsibilities and program flow organized, in a graphics engine?


texts:
By far, the biggest problem that has always dawned on my when programming games is how to structure my code. It just becomes an incredible mess, after a while. The reason for that is because I have no idea how different classes should interact with each other.

For example, say I have a Player class, a PlayerInput class and a Map class. The Player class contains information as to the location of the player, whereas the PlayerInput class handles changing that location, but by first making sure it is within a walkable area, using the Map class. How should I structure this?

My usual approach is to pass these components, as parameters, in the constructors of the parameters that need them, like so:

var map = new Map(); var player = new
Player(); var input = new
PlayerInput(player, map);

The problem with that is that it quickly gets messy; when you add new components, you have to go through your constructors and update them, and it doesn't work well if you have mirroring references:

var physics = new Physics(input); //Oops, doesn't work
var input = new Input(physics);

How should I manage my game objects and components?


texts: Reuse and Interact With Multi-Layer Tile Maps

texts:
I'm new to game development and try to make a game where buildings are created in tile maps. My problem is that I need to interact with these buildings and I want to reuse the buildings I created.
Now I would like to export these two layers to a single sprite or prefab to create multiple buildings and to make them clickable.
Is there a way to achieve this or do I have the wrong approach?
EDIT:
My current setup looks like this:
Two tile maps: One tile map contains the wall of the building. Another tile map contains decoration like door or window.
My problem is, that I am not able to export these tile maps as one prefab to reproduce it or to attach scrips.
I am looking for a way to combine these two layers into one resource (=The building with all its decorations, doors, windows), so that I can place them anywhere I want and make them clickable as a game object.


texts: UNITY: How do I use SetTile() with a tile asset/ scriptable tile?

texts: How do I use Tilemap.SetTile() with a tile asset? I want to use it for scriptable tiles in the 2d-extras package, such as rule tiles, weighted random tiles, and animated tiles. How would I 1. get inspector reference of this scriptable tile, and then 2. use SetTile() with it? Thanks for your attention.


texts:
I saw this subject several times, however I will wish better understand.

I am working on the development of a 2d game like a little MMO. (Currently I only do  research). I see people who says it's easier to use TCP for all the game. But is it really viable ?

In my mind, what I would have made is to use UDP in multicast. What about this solution ?

Thank you !


texts: AudioSource NullReferenceException: Object reference not set to an instance of an object

texts:
I honestly don't understand what's going on. This was working perfectly fine yesterday. I have a GameObject in my scene that has an AudioSource attached. The AudioSource has a dragged in .wav file in it's AudioClip section. The GameObject also has a script attached. The script looks like:

using UnityEngine;
using System.IO;

public class MyData : MonoBehaviour {
    AudioSource audio;

    // Use this for initialization
    void Start () {
        audio = GetComponent<AudioSource>();
    }

    void Update() {
        if (audio.isPlaying) { /* stuff */ }
    }
}

The script compiles file, the audio plays fine, I've quadruple checked everything, but I keep getting the error "NullReferenceException: Object reference not set to an instance of an object" at the audio.isPlaying line.


texts: How does a custom physics engine connect to a tile graphics engine?

texts:
I’ve been looking into adding physics to my tile based side scroller game, and it seems like the best option might be to write my own engine to handle things like collisions and gravity due to the simplicity of what it is I need.

I mostly understand the math that I need and some of the techniques to get the functionality I want (such as slopes), but the part I'm still missing is how the physics relates to the graphics, as well as how to actually implement that connection.

All that I've seen is that physics and graphics are separate, but are updated together (the textures/animations change according to the interactions from the physics engine). Aside from that, however, I have very little idea what I'm doing.

My question is: When it comes to a tile-based game, how do you handle physics bodies and their creation? And on top of that, what would be an efficient way to connect the two engines to one another?


texts: Getting the Bounds of a 2D Cameras View with Zoom

texts:
I am using a 2D camera, which does rotations and zoom. Currently, I am using the following to get my MinX, MinY, MaxX and MaxY...

    public float MinX
    {
        get
        {
            return pos.X - gameEngine.screenWidth / 2;
        }
    }
    public float MaxX
    {
        get
        {
            return pos.X + gameEngine.screenWidth / 2;
        }
    }
    public float MinY
    {
        get { return pos.Y - gameEngine.screenHeight / 2; }
    }
    public float MaxY
    {
        get { return pos.Y + gameEngine.screenHeight / 2; }
    }

How would I now take into account Zoom? Default Zoom is 1.
I think this will require Matrices, but any help is appreciated.


texts:
I'm currently developing a game, and I'm in a process of experimenting with various data structures to support my game model and simulation.

Here are some of the requirements:

Grid structure where every node will have exactly 4 neighbors, if revealed.
Infinite structure(max_int), with ability to dynamically add nodes
Ability to find all neighbors of a specific node
Ability to find all outer empty spots around existing nodes ( basically outline around graph)
Pathfinding

This is an example of how it should look. Red node will be starting point. Depending on a player's direction of movement, other nodes will be revealed and inserted into a graph. Also there is no restriction to movement between nodes as long as they are neighbors.

Current structure looks like this:

Node - containing [x,y] position in grid and data pointer, custom hash function for only [x,y]
Grid - set containing all nodes.

Now, in my testing, with the structure above, the bottleneck for 250x250 grid is finding neighbors, which takes a lot of time. BFS and DFS traversing is also slow due to the process of finding neighbors.

What are your suggestions for this kind of data structure ?

Edit 1:

Here are some of the ideas i was thinking about.
Btw already using hash_set(unordered_set) for storing nodes. Maybe i should switch to unordered_map, that way i could directly search by providing only [x,y]

Node could keep pointers to all neighbors like a cache, when adding new nodes, i could update old nodes with new neighbors, this way node will have direct access to neighbors.

As suggested, by using small chunks, i could possibly waste memory, because in worst case scenario only one node could be explored in a single chunk.

I was definitely thinking about quad-tree, this way i could use it in two different aspects(model searching/updating and rendering).


texts: I' relatively new to modeling, so this might be a simple question to answer. I'm having trouble trying to cross edges. I've placed a screenshot below of what I'm trying to accomplish (made in SketchUp). It's a box with to edges along the diagonals of each face. Is there a simple way to do this in 3ds Max? Thanks in advance.


texts: elongate or scale limbs of a model in XNA

texts:
I'd like to create one model that I import into an XNA game.

I'd like to be able to copy this model and make programmatic modifications to it during execution (with the intent of using the same model to represent multiple characters in the game). For example, I'd like to make the legs slightly longer or shorter, or the waist slightly fatter or thinner, or the head slightly smaller or larger.

I know how to use transforms to modify a mesh, but it seems that what I need here is to apply a transform to only a subset of vertices in that mesh. I have no idea how to do this in XNA, or if it's even supported.

Two questions:
 1) is functionality like this supported in XNA?
 2) if so, what kind of methods are used to obtain the desired result?

(note, this was crossposted from stackoverflow, this forum was recommended as a better place for my question)


texts: How to create scrolling input text field using Unity UI

texts:
How to create scrolling input textfield using UI

in Unity 4.6.6

problems in my project are

1.Cursor is not masking

2.Scrollbar size is automatically become 0 to 1 size

3.Scrollbar is not working after assigning in "Scroll Rect".

Here is my sample project

Thanks in advance .


texts: Can I remove the "powered by COCOS creator" message from my game?

texts: Is it legal to remove powered by COCOS creator in the page where the html is exported and also in the splash screen?


texts: Sea water shader using only fragment processor

texts: I have a game that runs on mobile devices (OpenGL ES 2.0) and for which I would like to create some sea water using the shaders. Now, the plane on which the sea water texture will be has only 4 vertices and I need it to remain like that (because of performance issues). So, I think, my only option is to simulate the water from the fragment shader.  At conceptual level, how should I do it? I must mention I'm a beginner with the programmable pipeline (I barely learned the language, in some extent) and have no idea where should I start.


texts:
I am generating a path using pathfinding.js. This returns a path of node coordinates from a matrix. Example:

var matrix = [[0,0,0,0], //0 are passable, 1 are obstacles
              [0,1,1,0],
              [0,1,1,0],
              [0,0,0,0]]

var path = [[0,0],[0,1],[0,2],[0,3],[1,3]] etc.

I now wish to convert this to path to something like, takeoff(), turnLeft(), forward(4) etc.

What this process called, I have had a look at many programming books and guides but they seem to ignore this method or miss it out. I also had a go at it myself but can't figure out the direction of unit that is being moved along the path.


texts: How to share some elements of array with different players on Photon in the same Room? Unity3d

texts:
I want to assign cards to different players in the room. I've a Class "Cards" that contains an array of 52 cards like this: "2_of_spades","3_of_spades"....... and so on. All i want is to assign random indexes or values to different players on the basis of which I'll instantiate Cards Sprites. How can I do that?
I've heard that there are RPC calls but how do I manage to make a "Middle Man" script that would deal with different players?


texts:
I am developing a game, but as I am working on it alone, the amount of content I can create is very limited. Because of that I want my game to be modded, for this purpose I am planning to create a complete modding API which would be exposed for lua scripting. I would also create tutorials to get people started. And the "Original" game would also be a "mod"(similar to Warcraft III maps) .

My question is: What can a developer do to encourage modding of its game?

PS: my game is a sandbox-ish multiplayer survival(most things are procedural).


texts:
I'm creating 3D Game Editor for my own use. As rendering i took Ogre3D and MFC as UI.

I faced with architecture problem.

I am using Document/View architecture and for each Doc. i create new SceneManager and for each View i create own viewport, camera, my own local Input manager which send input data to local camera. Also it's sending input data and pointer to SceneManager to global ToolManager which contains some base tools like Move, Select etc. and the pointer to active tool, if it's NULL he is sending input to SelectTool by default.

I'm only at start but i'm thinking of the future.
I think that this strategy of passing some data to the global manager is not so good how it looks now. Can you give me some design advices or articles and share with me your experience.

Thank you for your time.

Edit:

I think that plugin architecture would give a lot flexibility and it`s like all editors do. But i never before faced with that. So i will try to tell u what i think about it.
Host App contain

PLuginManager:

load/unload plugins
base interface to add frame/window and other UI
base interface to communicate with other plugins

EventListener

collect all events and EventListeners
send specific events to it listener

It's all what host app contains.
But, how to implement it? I mean all communication. How to load and save files. Edit object with different plugins. I'm thinking to use QT, is it better than MFC or wxWigets.

Can you give me some advices please.


texts: Import a 3D animation into an android game

texts:
I want to import a skinned and animated character model built with bender into an android game. The animations can be: idle, walk, run ...etc

I've seen a related question but it's only about importing a static model: https://stackoverflow.com/questions/204363/is-there-a-way-to-import-a-3d-model-into-android

But I don't see how to import a set of animation with tweened frames.

Any ideas, resources or tutorials about how this can be achieved ?

 Edit:
After some further searching I've found this library that claim to provide model loaders for md5 files.
http://code.google.com/p/libgdx/

Edit2 (2011 12 16):
I tested libgdx mentionned above And it actually works well for now, I can render a walking animation from md5 models with a good framerate, but the model loading time is quite long. For a large amount of models and frames, I think switching to binary formats will become necessary.


texts: Texturing edges of a procedurally generated polygon

texts:
I'm generating a polygon from code to display unit ranges in my game. Here's how it looks so far:

I would love to be able to now use my texture and only apply it to the edges of this polygon (imagine a stroke with no fill). Could someone point me in the right direction with this issue?


texts: Java Angle Math: Calculate how near the player looks to an entity

texts:
I am programming a Minecraft Bukkit plugin and need a way to calculate an input number from 0 to 360 for displaying a custom compass / radar. So if the player directly looks at the object (shouldn't handle viewing height or position height), this number would be 0 and if the player's back is looking on the object it would be 180.

I already successfully calculated both numbers I guess I need:

The absolute looking angle of the player. Is 0 when the player looks in north direction and 180 in south direction.
The location angle between the player's position and the object's position. Using Math.atan2 to get the angle between [X, Z] of these locations.

Both values seem to be calculated correctly. But I can't find out what to do to get the number I described at first. Tried substraction, addition. Any ideas?


texts: How can I implement a dialogue where the words appear as if they were being typed?

texts: I'm planning on putting a dialogue system into my game, I don't really work with surface so my way of implementing SDL_Ttf is by turning it into a texture, in other words, every paragraph would be shown within the rect, is there a way to make the words appear as if they were being typed?


texts: How to implement different weapons in player's hands?

texts:
What's the general approach to support variety of weapons in player's hands?

I currently have a 3d model that has empty hands. Should I have separate weapon models that I will just create and render into players hands in the game, or should I implement them in the actual model instead?

If they are not in the model, then how do I make the weapon appear in the right position, especially when considering that I want the player to have a walking animation and perhaps running too.


texts: How to apply physics when you have sub frame state changes?

texts:
I'm currently calculating my physics every 1/100th of a second and using a state machine to manage the current state of the player.
In my main loop I'm checking user input and transitioning the state as needed and then my physics code checks the state to apply the appropriate forces.

Pseudo:

if (fsm.state == walking) {
    velocity += walkVelocity;
}

However, the issue I think I've noticed with this is; what if a full state transition occurs between two physics frames. For example the user taps jump so quickly they transition from jumping to falling happens so quickly that the physics code hasn't got a chance to see that a jump was requested and therefore doesn't apply the change in velocity.

This is a simple example, but I'm feeling that states maybe shouldn't be used this way. Maybe the key presses themselves need to be fed directly into the physics code (so that it can have access to durations and order of events) and then it (the physics code) updates the states accordingly.

Is this the common way of arranging flow? Or am I missing something? I.e. should it be:

  Input -> state change -> physics

Or should it be more like:

  Input -> physics -> state change

I've seen state machines used with event systems before. So state changes are raised as events which subscribers can respond to. However the physics code still needs to run at fixed timesteps so it needs to be able to query for 'things which have occurred'.


texts: differences betwen game resolution in a different display resolution

texts:
my game is not supported on the other devices with a different resolutions. for example may character is 140w X 55h pixels which is ok on a 4 inch display but it goes wide when i tested my game on a device with 4.7 inch display. how can i make a correct character for 4.7 or more inch displays?
i am using cocos2d-x engine. i want to see if it has a automatic synchronize tool or no. i my self must do it manually ?


texts:
I am currently developing a game that pulls in the basic ideas and concepts from 3 other games.
I want to make a trailer, and can I put in the trailer something like this:

  Pulling Game Concepts from:   ...Pokemon   ...Fable   ...and Harvest
  Moon

Can i do this? Or would I have to get permission to even reference them?


texts: Ease action to simulate a clank in a moving or rotating device near end of the trajectory

texts:
You know those mechanisms that moved or rotated, and then just a few millimeters near the end of the trajectory they oppose a bit of resistance and then clank to the final position.
I want to simulate that clank with an ease function that can be combined with the standard ease actions. The link is for reference to some examples of ease transition functions, but I just need the pseudocode like this:
float clankActionTime(float t) {
    if (t > 0.9)
        return (0.5*sin(10.0*t*2.0*M_PI)+2.0*10.0*t)/20.0;
    return t;
}

That is what I have so far, which gives this graph for t between 0 and 1.

But I want something more like this:

Where A and B are parameters passed to the ease function to indicate where to star the clank and how deep is the valley near the end of the curve, respectively.


texts:
I'm working on an isometric city generator, and I am looking for a little push in the right direction. I'm looking to randomly generate roads on an isometric plane. I have never done path making before, and I've Googled it and didn't find any articles relating to what I am trying to do.

Basically, my program generates a random isometric city and I am hoping to add roads to that.


texts: Generating a UV map for a procedural mesh

texts:
I have created a procedural low poly rock mesh and now I would like to apply textures on it.

I have the 3D-coordinates of every vertex of the mesh but that's about it. How would I automatically generate a UV map for this mesh, since this list of vertices will change every time I generate a rock? How do I get all these faces correctly mapped in a (1,1) square?

I am working in Unity3D if that helps.

Thanks,

Alex

EDIT: Preserving the face shapes/sizes is priority! I don't want distortion at all. The texture will be generally just the same color with some darker/lighter spots so every edge could be used as a seam. Faces can overlap! I just want all the faces in one 2D box (1,1), with the correct dimensions.

EDIT 2:

I have this code:

    Vector3[] verts = mesh.vertices;

Vector2[] uvs = new Vector2[verts.Length];

for (int i = 0; i < uvs.Length; i++)
{

    uvs[i] = new Vector2(Mathf.Abs(verts[i].x), Mathf.Abs(verts[i].z));

}

Which gives me the following UV map:
[![enter image description here][2]][2]

EDIT 3:

  float scaleFactor = 0.5f;

int[] tris = mesh.triangles;

Vector3[] verts = mesh.vertices;
Vector2[] uvs = new Vector2[verts.Length];

// Iterate over each face (here assuming triangles)
for(int index = 0; index < tris.Length; index += 3)
{
    // Get the three vertices bounding this triangle.
    Vector3 v1 = verts[tris[index]];
    Vector3 v2 = verts[tris[index + 1]];
    Vector3 v3 = verts[tris[index + 2]];

    // Compute a vector perpendicular to the face.
    Vector3 normal = Vector3.Cross(v3 - v1, v2 - v1);

        Debug.Log("surface " + index/3 + " : " + (normal*0.5f).magnitude);

    // Form a rotation that points the z+ axis in this perpendicular direction.
    // Multiplying by the inverse will flatten the triangle into an xy plane.
    Quaternion rotation = Quaternion.Inverse(Quaternion.LookRotation(normal));

    // Assign the uvs, applying a scale factor to control the texture tiling.
    uvs[tris[index]]     = (Vector2)(rotation * v1) * scaleFactor;
    uvs[tris[index + 1]] = (Vector2)(rotation * v2) * scaleFactor;
    uvs[tris[index + 2]] = (Vector2)(rotation * v3) * scaleFactor;
}

The red triangle on the left and the dark blue one on the right should be the same shape/size:

EDIT 4:

Mesh mesh = new Mesh();
mesh.name = "RockMesh";
List<int> Triangles = new List<int>();

var vertices = Vertices.Select(x => new Vertex(x)).ToList();

var result = MIConvexHull.ConvexHull.Create(vertices);
mesh.vertices = result.Points.Select(x => x.ToVec()).ToArray();
var xxx = result.Points.ToList();

foreach(var face in result.Faces)
{
    Triangles.Add(xxx.IndexOf(face.Vertices[0]));
    Triangles.Add(xxx.IndexOf(face.Vertices[1]));
    Triangles.Add(xxx.IndexOf(face.Vertices[2]));
}

mesh.triangles = Triangles.ToArray();

EDIT 5:

I had to move the code a bit but it finally works now! Like you guys predicted, the seems are not optimal, but I'm happy how it is now. Thanks!


texts: How can I author objects with perspective that fit into a tile-based map but span multiple tiles?

texts:
I'm creating a tilemap city and trying to figure out the most efficient way to create unique building scenes. The trick is, I need to maintain a sort of 2D, almost-top-down perspective, which is hard to do with buildings or large objects that span multiple tiles.

I've tried doing three buildings at a time, and mixing and matching the base layer and colors, like this:

This creates a weird overlapping effect, and also doesn't seem that efficient from a production standpoint. But it was the best way to have shadows appear correctly on the neighboring buildings.

I'm wondering if modular buildings would be the way to go? That way I can mix and match any set of buildings together as tiles:

I guess I would have to risk some perspective and shadowing to get the buildings to align correctly.

What sort of authoring process could I use to allow me to create a variety of buildings (or other objects) that maintain this perspective while spanning multiple tiles worth of screen space? Would you recommend creating blank buildings, and then affixing art overlays as necessary to make the buildings unique? Or should they be directly part of the building tile (for example, create a separate tileset of buildings signs and colorings)?


texts: Complex shading using one single (small) texture

texts:
Recently I stumbled upon a demo reel in UDK about how one can attain beautiful results using just one (rather tiny) texture that's being sent to the shader pipeline. The famous link is this one.

Basically, the author states that they've used just one texture and give a snapshot of the technique here.

I see that every RGBA channel contains different grayscale information.. and that info could be used to inside a shader to obtain a colour blended output. The problem is that the reel displays a fairly complex scene. To top that, the author even makes use of a normal map. How did they manage to fit a normal map in an already cluttered texture? It makes sense to have a half-space normal map by using only RG from an RGB texture, but what about the rest of the information? Since it was proven to be possible, could someone please explain how it was done (the big picture, not the dirty details!)!?

Here's the texture being used. Click to see in full size.


texts: One big asset file or many small asset files?

texts:
I'm working on a game and I'm wondering if it is better for performance and memory usage to have one large file containing all my assets (the assets are in a custom format) with a look up table at the front telling the location of the asset in the file or is it better to have each asset in its own file?

Thanks,
Philip


texts: Select a block of tiles from tilemap by click and dragging

texts:
I'm creating my first game in Godot 3.1, a top-down 2D sim game where you can build rooms on a space station. I am using a tileset I created inside a TileMap node. I placed a script inside the node that checks for the mouse position in the world, converts it into a tilemap coordinate, then loads a tile into that tilemap coordinate.

func _input(event):
if (event is InputEventMouse):
    var button = event.get_button_mask()
    if (button == 1):
        var tile_pos = world_to_map(event.position)
        var name = _tileset.tile_get_name(0)
        set_cellv(tile_pos, _tileset.find_tile_by_name(name))

Works like a champ! As long as the left mouse button is held down, any tile the mouse pointer touches is filled with the tile from the tileset.

Now I am trying to expand this function so that I can click the world and drag across several tiles to form a rectangle or square, then have all of the tiles inside the selected area filled with the selected tile.

func _input(event):
if (event is InputEventMouse):
    var button = event.get_button_mask()
    if (button == 1):
        var tile_pos = world_to_map(event.position)
        if (dragStart == Vector2(-1,-1)):
            dragStart = tile_pos
        var name = _tileset.tile_get_name(0)
        if (dragStart != Vector2(-1,-1) && dragStart != tile_pos):
            var newX = dragStart.x - tile_pos.x
            var newY = dragStart.y - tile_pos.y
            while (newX != 0 && newY != 0):
                var next = Vector2(-1,-1)
                if newX > 0:
                    next = Vector2(dragStart.x - 1,dragStart.y)
                    newX = newX - 1
                elif newX < 0:
                    next = Vector2(dragStart.x + 1,dragStart.y)
                    newX = newX + 1
                elif newX == 0:
                    if newY > 0:
                        next = Vector2(dragStart.x,dragStart.y - 1)
                        newY = newY - 1
                    elif newY < 0:
                        next = Vector2(dragStart.x,dragStart.y + 1)
                        newY = newY + 1
                print(next)
                set_cellv(next, _tileset.find_tile_by_name(name))
    else:
        dragStart = Vector2(-1,-1)

However, it seems to only load some of the tiles and functions sporadically. Am I not understanding how the system iterates through the while loop or am I missing something else?


texts: Combine framebuffer-textures to default framebuffer

texts:
I know frame-buffers are not textures themselves, but they do contain a texture, given they are set up correctly, which I believe mine are, as:

(status == GL_FRAMEBUFFER_COMPLETE)

returns true.

The reason I am using multiple frame-buffers is so that I can perform some post-processing on individual objects/layers - is this even a best-practice approach?. So I render to a bunch of textures, and to not end up with a black screen, due to never rendering to the default frame-buffer, I need to somehow combine the frame-buffers/textures into the default frame-buffer.

My naive approach would be to bind the default frame-buffer and then just make a simple shader-program that would write each texture back to the screen.

This seems like a task that could be optimized through some built-in function specially for this as it must be a standard thing now'a'days, so what is the correct way to combine a bunch of frame-buffers/textures into one (the default frame-buffer)?


texts: How to properly rotate towards a local point in Unity C#? (a local LookAt)

texts:
I am having a nightmare trying to make a child object rotate towards a given point of its parent object, similar to what is possible at the world level when using LookAt.

The problem is that most functions related to rotating in Unity C# do not work for local level. In the description of function transform.Rotate one can have the impression that it allows that, trough passing the Space.Self parameter. However, to use that function one has to know the 3 angles between the 2 points of interest. And there is no function that allows such calculation.

Anyone could please help implementing a local LookAt?


texts: In random loop button dont work properly

texts:
I have this code to add 10 point if someone click the button and change the question. But it returns 10 point every time. I want to make it 10,20,30,40... etc.

IEnumerator TransitionToNextQuestion() {

            unAnsweredQuestions.Remove(currentQuestion);
            yield return new WaitForSeconds (timeBetweenQuestions);
            SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }

        public void addPoint(int addPoint) {
            point = point + addPoint;
        }

        public void ButtonDown() {
            addPoint (10);
            Debug.Log (point);
            StartCoroutine (TransitionToNextQuestion());

        }


texts: How attach a model with another model on a specific bone?

texts:
I meet a difficulty attached to a model to another model on a "bone" accurate.
I searched several forums but no result. I saw that many people have asked the same question but no real result see no response.
Thread found :

How to attach two XNA models together?

How can I attach a model to the bone of another model?

https://stackoverflow.com/questions/11391852/attach-model-xna

But I think it is possible.

Here is my code example attached a "object" of the hand of my player

private void draw_itemActionAttached(Model modelInUse)
    {
        Matrix[] Model1TransfoMatrix = new Matrix[this.player.Model.Bones.Count];
        this.player.Model.CopyAbsoluteBoneTransformsTo(Model1TransfoMatrix);
        foreach (ModelMesh mesh in modelInUse.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                Matrix model2Transform = Matrix.CreateScale(1f) * Matrix.CreateFromYawPitchRoll(0, 0, 0);

                effect.World = model2Transform * Model1TransfoMatrix[0]; //root bone index
                effect.View = arcadia.camera.View;
                effect.Projection = arcadia.camera.Projection;
            }
            mesh.Draw();
        }
    }


texts: Decide whether bot is approaching or leaving

texts:
Consider a static obstacle placed in 3 Dimensional coordinate plane. A moving bot is programmed to pass through it. We know the position of obstacle. We also know the current position and current velocity of moving bot. Say, position and velocity are given as 3D vector.

How to decide whether the bot is approaching the obstacle or leaving the obstacle?

I think, the relative velocity should be able to differentiate it? Any approach please.


texts: My game crashed... Access Violation (0xc0000005)

texts:
I guess this is the first official crash I've had in Unity (that is not just an infinite loop.) The game works just fine in the editor but when build and run it, the game won't even start.

I just keep getting this error message:

So I check the folder specified but I have no idea what I'm looking at if I'm completely honest with my self. I see a bunch of directories and stuff but that's about it. I don't know how to read an error log but I'd like to. This whole game is a learning experience so I would to learn how but Idk what to do.

this is the error log : Here

If need be I'll put it in the question but I'd like to avoid making this too long. If you have any questions about my code you need to know let me know.


texts: How to handle a player's level and its consequent privileges?

texts:
I'm building a game similar to Mafia Wars where a player can do tasks for his gang and gain experience and thus advancing his level.
The game is built using PHP and a Mysql database.
In the game I want to limit the resources allowed to player based on his level.
For example:
________| (Max gold) | (Max army size) | (Max moves)  | ...
Level 1 |    1000    |       100       |      10      | ...
Level 2 |    1500    |       200       |      20      | ...
Level 3 |    3000    |       300       |      25      | ...
  .
  .
  .

In addition certain features of the game won't be allowed until a certain level is reached such as players under Level 10 can't trade in the game market, players under Level 20 can't create alliances,...etc.
The way I have modeled it is by implementing a very loooong ACL (Access Control List) with about 100 entries (an entry for each level).
However, I think there may be a simpler approach to this seeing that this feature
have been implemented in many games before.


texts:
Super quick intro. I am making a terrain generator (With a MC exporter mostly to debug). For the islands I am creating a map with points, and create a Voronoi diagram from it. Each intersection (Where lines of the shapes meet) has a different height, depending on the distance to the coast. The coast itself is elevation=0.

However, whatever I try, I keep getting weird heightmaps. (I can't link more than two images, so I will explain). You can clearly see the difference between each site, yet they are slightly sloped.

In-game this looks like this:

The red blocks that stick out is the height of the intersection.
Sites are created by references to the intersections, since they have IDs.

The code I am using at the moment:

Point p = new Point(x, 1, z);

        double[] distances = new double[points.length];
        double[] percentages = new double[points.length];
        double[] elevations = new double[points.length];

        int max = 0;
        for(int i=0; i<points.length; i++)
            if(parent.getIntersections().fromIndex(points[i]).getElevation() > max)
                max = (int)parent.getIntersections().fromIndex(points[i]).getElevation();

        double totaldist = 0;
        for(int i=0; i<points.length; i++) {
            distances[i] = parent.getIntersections().fromIndex(points[i]).getLocation().surfaceDist(p);
            totaldist+=distances[i];
        }

        for(int i=0; i<points.length; i++){
            percentages[i] = (distances[i] / totaldist);
        }

        for(int i=0; i<points.length; i++)
            elevations[i] = (percentages[i] * (parent.getIntersections().fromIndex(points[i]).getElevation()));

        double heightTemp = 0;
        for(int i=0; i<elevations.length; i++)
            heightTemp += elevations[i];
        heightTemp = max-heightTemp+max;

        int height = (int) heightTemp - 3 + parent.getConfig().getSeaLevel() ;
        height = (height>255 ? 255 : height);

The code's quite weird and unorganized since I pretty much tried anything I could come up with.
"points" is an array containing the reference IDs to the correct intersections
"parent.getIntersections().fromIndex(int index)" is the way to retrieve an intersection from the index/reference id.
"p" is the point to get the altitude/elevation from.
"Intersection.getElevation()" returns the elevation (Anything above sea level).

Sorry if this is real vague, I have no clue on how to explain this properly.


texts: How is custom-written music generally licensed for a small game?

texts:
I am relaunching my career as a game musician; previously I have done a little bit of licensed work and writing music for game jam-type games, after having written music as a secondary job duty for my full-time job at various game studios. As I am entering into the world of freelance game music composition, however, I am not sure what sort of license terms are common.

In particular, one developer I was in contact with wanted me to do the music entirely as a work-for-hire; I would retain the ability to showcase the music I do for him on my portfolio and the like, but I would not be allowed to, say, release a soundtrack album that contains the work, and he would retain the rights to re-license the music as he sees fit (including to other developers or for entirely different purposes). This doesn't seem to be in keeping with how I've seen other game music work, legally-speaking; if I do agree to these terms I would of course charge more than I would for music that is licensed, rather than sold.

I would, on the other hand, be totally fine with providing an exclusive game license for the music – that is, he would be the only one allowed to use my music within a game, but I would retain the rights for publication in other media. This seems to be how most indie game music is licensed, judging by how the original artists release their OSTs on Bandcamp and iTunes and the like.

Are there any standard contracts for game music licensing in various circumstances, or at least an explanation of the standard practices involved?


texts: How does one get sprites to hide/unhide using OnMouseDown() in Unity?

texts:
I'm right now using Unity for a school project and I need to be able to hide and
unhide sprites for "expansions".

I've looked all over the internet for this and I can't seem to find an answer.

Here is the script so far:

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

[DisallowMultipleComponent]
public class addBlock : MonoBehaviour{

  void OnMouseDown()
  {
     Debug.log(gameObject.name);
  }
}


texts: C# store functions with parameters in a List

texts:
I want to store functions with parameters in a List, so that I can call them at a later stage.

Let's say (this is rough code)

void Func1(int index)
{
   Debug.Log("Func1"+index)
}

void Func2(int index)
{
   Debug.Log("Func2"+index)
}
.
.
.

void Store(Func1(1))
{
  list.Add(Func1(1));
}

void Replay(int position)
{
  list[position](); // this calls the function with the parameter
}


texts: How would one construct a realistic "infrared vision" effect?

texts:
How would you go about constructing a realistic infrared vision effect with shaders? By realistic I mean one that looks realistic, like this example.

I have an idea about making a texture to determine how much heat a material emits and then determine by using the dot product of normal and view vector how much of that heat reaches the viewer but I'm not even sure that this is how thermal vision even works so I wanted to check if there's a better approach before starting to implement something that might be entirely wrong.


texts:
I've just gotten a triangle collision object in using the Separate Axis Theorem, the triangle has a 45 degree slope and resloves collision detection via the projection method. The actual collision detection works fine, but I'm having an issue where the character keeps slipping down the slope when he runs up or goes down it.

These are the number for the characters movement. I know I should be doing something with either the part of the Y velocity or somehow changing the x velocity but not sure what.

The number for the velocity

private float accerlation = 0.25f;
 velocity.X = velocity.X - accerlation

private float superaccerlation = 0.3f;
velocity.X = velocity.X - superaccerlation

How the collision is being resolved.

if (collision == TileCollision.LeftSlope)
{
    Vector2 triDepth = RectangleExtensions.GetIntersectionDepthTriLeft(bounds, tileBounds);

    if (triDepth.X != 0 && triDepth.Y != 0)
    {
        isOnSlope = true;
        Position = new Vector2(Position.X + triDepth.X, Position.Y + triDepth.Y);
    }
    else if (triDepth.X != 0 && triDepth.Y == 0)
        Position = new Vector2(Position.X + triDepth.X, Position.Y);
    else if (triDepth.X == 0 && triDepth.Y != 0)
    {
        headOnRoof = true;
        Position = new Vector2(Position.X, Position.Y + triDepth.Y);
    }

    bounds = BoundingRectangle;

}


texts: Use Unity Handles for interaction in the scene view

texts:
I want to give an object with a specific script arrows to do special functions in the scene view. I have gotten Unity to render the arrows but I have no idea how to actually handle mouse events. The docs appear to say that I should be able to identify what receives a mouse down event by calling HandleUtility.nearestControl however when clicking on different arrows in the scene view I get the same ControlId (which i'm guessing is the gameobject itself). How are you supposed to know/deal with mouse events properly?

Code:

[CustomEditor(typeof(Script))]
class SceneGui : UnityEditor.Editor
{
    void OnSceneGUI()
    {
        if (Event.current.type == EventType.Repaint)
        {
            Transform transform = ((Script)target).transform;
            {
                Vector3 pos = transform.position + Vector3.left * 2;
                Handles.color = Color.yellow;
                Handles.ArrowHandleCap(3000, pos, Quaternion.LookRotation(Vector3.left),
                    2, EventType.Repaint);
            }

            {
                Vector3 pos = transform.position + Vector3.right * 2;
                Handles.color = Color.red;
                Handles.ArrowHandleCap(3001, pos, Quaternion.LookRotation(Vector3.right),
                    2, EventType.Repaint);
            }

            {
                Vector3 pos = transform.position + Vector3.forward * 2;
                Handles.color = Color.blue;
                Handles.ArrowHandleCap(3002, pos, Quaternion.LookRotation(Vector3.forward),
                    2, EventType.Repaint);
            }

            {
                Vector3 pos = transform.position + Vector3.back * 2;
                Handles.color = Color.cyan;
                Handles.ArrowHandleCap(3003, pos, Quaternion.LookRotation(Vector3.back),
                    2, EventType.Repaint);
            }
        }
        else if (Event.current.type == EventType.mouseDown)
        {
            Debug.Log(HandleUtility.nearestControl);
        }
    }
}


texts: Component entity system - Updates and call orders

texts:
In order to get components to be able to update every frame (and leave this functionality out of components that don't need to) I got the idea to make an UpdateComponent component.  Other components like MovableComponent (which holds velocity) would inherit from the IUpdatable abstract class.  This forces MovableComponent to implement an Update(gametime dt) method and another RegisterWithUpdater() that gives UpdateComponent a pointer to the MovableComponent.  Many components could do this and then UpdateComponent could call all of their Update(gametime dt) methods without having to care about who or what they are.

My questions are:

Does this seem like anything that is normal or used by anyone?  I cannot find anything on the subject.
How could I maintain an order to the components like physics then position change?  Is this even necessary?
What are other ways of insuring that components that should be process every frame are in fact processed?

EDIT
I think I will be concidering how to give the entity manager a list of types that are updatable. Then ALL of the components of that type can update rather than managing it per entity (which are just indexes in my system anyway).

Still.  My questions remain valid to me.  I don't know if this is reasonabl/normal, or what others tend to do.

Also, the people at Insomniac are awesome!
/EDIT

Boiled down code for previous example:

class IUpdatable
{
public:
    virtual void Update(float dt) = 0;
protected:
    virtual void RegisterAsUpdatable() = 0;
};

class Component
{
    ...
};

class MovableComponent: public Component, public IUpdatable
{
public:
    ...
    virtual void Update(float dt);
private:
    ...
    virtual void RegisterWithUpdater();
};

class UpdateComponent: public Component
{
public:
    ...
    void UpdateAll();
    void RegisterUpdatable(Component* component);
    void RemoveUpdatable(Component* component);
private:
    ...
    std::set<Component*> updatables_;
};


texts: Static body bridging two other static bodies

texts:
I have two box2d bodies like below,

What I need is to create another body that kind of bridges this two bodies. I am not looking for a box2d joint, but a body that will be like a bridge touching the rightmost point of the first body and the leftmost point in the second body, like in this image (excuse my paint skills).

Problem is, looks like I am not getting the co-ordinates and angles on how to create the third (bridge) body. Here's my code below,

  Body body1, body2, bridge;

BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(350 / Constants.PIXELS_TO_METERS, 0 / Constants.PIXELS_TO_METERS);

body1 = world.createBody(bodyDef);

PolygonShape shape = new PolygonShape();
shape.setAsBox(300 / Constants.PIXELS_TO_METERS, 300 / Constants.PIXELS_TO_METERS);

FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;
body1.createFixture(fixtureDef);

BodyDef bodyDef2 = new BodyDef();
bodyDef2.type = BodyDef.BodyType.StaticBody;
bodyDef2.position.set(1600 / Constants.PIXELS_TO_METERS, 0 / Constants.PIXELS_TO_METERS);

body2 = world.createBody(bodyDef2);

PolygonShape shape2 = new PolygonShape();
shape2.setAsBox(300 / Constants.PIXELS_TO_METERS, 500 / Constants.PIXELS_TO_METERS);

FixtureDef fixtureDef2 = new FixtureDef();
fixtureDef2.shape = shape2;
fixtureDef2.density = 1f;
body2.createFixture(fixtureDef2);

BodyDef bodyDef3 = new BodyDef();
bodyDef3.type = BodyDef.BodyType.StaticBody;

Vector2 a = new Vector2(body1.getPosition().x + 300 / Constants.PIXELS_TO_METERS, body1.getPosition().y + (300 + 50 / 2) / Constants.PIXELS_TO_METERS);
Vector2 b = new Vector2(body2.getPosition().x - 300 / Constants.PIXELS_TO_METERS, body2.getPosition().y + (300 + 50 / 2) / Constants.PIXELS_TO_METERS);

float distance = a.dst(b);
Vector2 bridgePos = new Vector2(a.x + distance / 2, a.y + 50 / 2 / Constants.PIXELS_TO_METERS);

bodyDef3.position.set(bridgePos);

float angle = (float) Math.atan2(a.y + 50 / Constants.PIXELS_TO_METERS, b.x);
bridge = world.createBody(bodyDef3);

PolygonShape shape3 = new PolygonShape();
shape3.setAsBox(distance / 2, 50 / Constants.PIXELS_TO_METERS);

FixtureDef fixtureDef3 = new FixtureDef();
fixtureDef3.shape = shape3;
fixtureDef3.density = 1f;
bridge.createFixture(fixtureDef3);
bridge.setTransform(bridgePos, angle);

This doesn't give the correct position or angle for the bridge, as it works for some body sizes and sometimes don't (yes, I have accounted for the hardcoded values for every change). I am not exactly sure what I am doing wrong. Any help?


texts:
I came across this term when searching for ways to visualize collection of voxels.
What is volumetric rendering  ? How is it different from normal surface rendering ? Are there any special advantages of using volumetric rendering ?


texts: Can I use real currency name/symbol as an in-game currency?

texts:
Can I use a real currency name (i.e USD, PKR) or symbol ($, Rs.) for my in-game currency with the same exchange value as original currency? I couldn't find anything about it in google play store policies neither in government websites.

Of course I have other options, I can call it gold or silver etc but I'm just wondering if it is allowed or not.


texts: NavMeshAgent is not calculating a new path

texts:
I have the following code that gets run when a game object collides with a trigger. When the object is created, it is created within an initial trigger which fires the SetNextWaypoint code below and it works fine.

protected NavMeshPath path;
protected NavMeshAgent agent = null;

void Start () {
    path = new NavMeshPath();
    agent = GetComponent<NavMeshAgent>();
}

public void SetNextWaypoint(Vector3 location){
    agent.ResetPath();
    path.ClearCorners();
    agent.CalculatePath(nextWayPoint, path);
    agent.SetPath(path);
}

Once the agent enters a new waypoint (it may not have reached its destination yet) SetNextWaypoint is called again and when it does the agent just stops where it is, and doesn't move anywhere.


texts: Self-set vs explicit goals and their efficacy

texts:
Just curious if anyone has an insight onto the efficacy of self-set goals as opposed to explicit ones in regards to player retention.

Content requirements aside are there any anecdotal or quantitative results on which method provides a more immersive experience for a player, and thus is more likely to keep them around and playing?


texts: My character moves right and left correctly, I want to know if it is possible to move character forward and backward to collect hearts   (I know that in 2d no z axis I want to know if it is possible or not? )


texts: Unity: How to resize a game object for a certain amount of time?

texts:
I've tried to make a coroutine like this

private IEnumerator applyPowerUp(string type, GameObject player)
{
    GameObject originPlayer = new GameObject();
    originPlayer = player;

    if (type == "Bigger")
    {
        Debug.Log("make it big");
        player.transform.localScale = new Vector3(1.25f, 2.9f, 0);
        player.transform.position = new Vector2(player.transform.position.x + 0.4f, player.transform.position.y);
        yield return new WaitForSeconds(5);
        player = originPlayer;
    }
}

The game object are getting bigger but after 5 secs it didn't turn back to its origin size.


texts: Creating and editing a .fnt file based on a PNG source

texts:
I am currently making a game, (obviously), with the LIBGDX Java Library. I have already made a font, (It's a PNG file, not a TTF or RTF), that looks something like this:

(It's a mockup, by the way.)

I've tried programs like Shoebox to create my font automagically, but it doesn't recognize my font.

Can someone explain how I can just make my own .FNT config file?

Thanks in advance!

Plug


texts: how can i get rotation vector from matrix4x4 in xna?

texts:
i want to get rotation vector from matrix to realize some parent-children system for models.

 Matrix bonePos = link.Bone.Transform * World;
 Matrix m = Matrix.CreateTranslation(link.Offset)
       * Matrix.CreateScale(link.gameObj.Scale.X, link.gameObj.Scale.Y,
                 link.gameObj.Scale.Z)
       * Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(link.gameObj.Rotation.Y),
                 MathHelper.ToRadians(link.gameObj.Rotation.X),
                 MathHelper.ToRadians(link.gameObj.Rotation.Z))
//need rotation vector from bone matrix here (now it's global model rotation vector)
        * Matrix.CreateFromYawPitchRoll(MathHelper.ToRadians(Rotation.Y),
                  MathHelper.ToRadians(Rotation.X),
                  MathHelper.ToRadians(Rotation.Z))
         * Matrix.CreateTranslation(bonePos.Translation);
link.gameObj.World = m;

where :
  link - struct with children model settings, like position, rotation etc.
 And link.Bone - Parent Bone


texts:
I have a large cubic bezier defined 2D polygon area which I need to render in DX11 real-time to create as many 4096x4096 textures as needed.
An average control point count would be around the 12k and I need to render it with a 16x resolution, meaning that for every unit of length, I would need 16 line segments.
This makes it impossible to triangulate the generated mesh as the shear number of polygon points would take seconds to triangulate.

I thought of tessellating the bezier polygon and then clipping it to fustrum but again, since we are talking about a lot of triangles that would be too slow for real time rendering (I need to be able to modify the bezier polygon real time).

To add insult to injury, polygon holes and Steiner points are a requirement as the color of the surface would come from the different points "depth".

Ideally, I would clip the bezier polygon (to fustrum or smaller sub-polygons) before tessellating but I don't know of a library that can do that.

The only "idea" I currently have is to cut any bezier segment to sub-segments shorter than 4 units, using the 64 levels of shader tessellation and then move the new vertices according to the control points but needless to say, this seems overly complicated and inefficient.


texts: Humanoid Rig Animations Not Playing Properly

texts:
Although I have seen a few questions that are similar to my own, none had specific or clear answers that actually solved the problem, so here I am.
Just recently, I have imported a rig from Blender into Unity, along with a few embedded animations. As you can see here: https://gyazo.com/54f5717fa71170b198a77d5458aad919 the animations imported fine and function normally with the generic rig. The moment I switch the avatar to a humanoid-type rig, however, the only part that moves is the heart, as it is not mapped in the rig: https://gyazo.com/0f9a0b9a1c2580b848733e980fb9fcef.
As Unity has told me many times now, this is due to the humanoid rig's muscle system thing which doesn't make any sense.
So my question here is, how does one make an animation that works on humanoid rigs? Did I somehow import the Blender animation wrong or am I supposed to use Unity's animator to do it (even though it doesn't work either)?


texts:
I developed an Android game using Unity3D and successfully published it in Play Store. But the apk size almost 30MB which is pretty big for my game. When I checked the Editor Log after the build, this is what I found:

Textures      2.5 mb     20.1%
Meshes        433.8 kb   3.4%
Animations    2.2 kb     0.0%
Sounds        3.9 mb     31.3%
Shaders       191.3 kb   1.5%
Other Assets  157.9 kb   1.2%
Levels        166.9 kb   1.3%
Scripts       1.2 mb     9.4%
Included DLLs 3.9 mb     31.5%
File headers  44.5 kb    0.3%
Complete size 12.5 mb    100.0%

I just don't understand how could the final build will weigh more than twice the size stated in the log


texts: How to translate a direction on the screen to 3D space?

texts:
EDIT:
Alright, I've figured out what's wrong. I'm calculating the direction vector properly with the below code:

//Get our ship position in screen space
Vector3 shipPos = Camera.main.WorldToScreenPoint(GameObject.FindGameObjectWithTag("Player").transform.position);

//Get the direction vector from our ship to our mouse
Vector3 direction = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0) - new Vector3(shipPos.x, shipPos.y, 0);

//Give the clone script our direction vector.
direction = Camera.main.transform.TransformDirection(direction);

This gives out the proper direction vector relative to our camera (I've tested it with a Debug.DrawRay()). The problem is, in order to get the bullets to orbit around the planet I'm using the below code:

//Rotate our bullet around the planet, our axis of rotation is the vector perpendicular to targetDir
transform.RotateAround(Ship_Motor.instance.planet.transform.position, new Vector3(-targetDir.y, targetDir.x, 0f), -speed * Time.deltaTime);

My calculation for an axis based on our direction works when the ship is right side up. However when I move it around to be at a different angle that's when things go wrong. So it seems as if my code for calculating the axis to rotate the bullet around is what I'm doing wrong. Does anyone have suggestions how I could fix it so that transform.RotateAround() would make the bullet start orbiting the planet in the direction it was fired off in?

ORIGINAL POST:

I'm making a top down shooter, however gravity is a bit weird in this game. At certain times the player may be upside down compared to global vectors, or at other odd angles.

Basically what I'm looking to do is get the player position in screen space, get a direction vector from that to the mouse so I know what direction the player should shoot, then translate that back to a 3D vector and have the player shoot that direction relative to the camera. Basically if the mouse is to the right of the player on screen, I want the player to shoot right.

The only problem with this is that when I translate the vector back to 3D, it's not always relative to the camera. And transform.transformdirection() doesn't appear to help.

Is there a way I could get a local vector from the camera and get the relative vector for the player? e.g. get the camera's local right vector, then figure out how that is for the player (possibly forward for the player or some such.)

I'm writing this in a hurry right now, I can add more details and exact code later if anyone requests it.