texts: How to blend two cameras when traveling through a portal in Unity3D

texts:
Before I get to my question, I know the most obvious solution would be to use the normalized view port rect, however I need more complex shapes than a rectangle, and I've looked in to using the view port rect and it seems to not be my solution.

EDIT:
Some people were confused by my question, let me go in to a bit more detail.

What's happening is as the player moves in to one portal, I create a clone FPS controller and move it out of the other. This gives me two cameras, and the view you see on the right above. It's just showing one camera, and clipping through the portal. What I want is something similar to this where the cameras blend to create the illusion of a smooth transition. What I want to do is delete everything from the green checker image to the left in the image below, and replace that with the other camera. That way you get the part of camera A's view that is peaking out of the portal, blended with the part of camera B's view that's peaking out of the other portal, to get one complete image. And as you move through the portal the cut changes appropriately.

I've been designing a portal system, I have everything down, including getting the player to smoothly move through the portal. My main problem now is getting that camera blend effect Valve does. I need two cameras to blend together seamlessly, as if you were poking your head through the portal. And it can't just be a rectangle, it has to match however the player is looking through the portal.

My best lead on this right now is to possibly project a depth mask shader behind each portal, then make the camera from the portal you're traveling to be depth only. Then somehow mix the two cameras. My main problem is figuring out exactly how I'd do this, how to make the second camera only render what's outside of the portal, and have the rest default to camera 1 to get one full screen projection.

If you could give me ideas, or explain how I may do this with the depth mask shader that would be a tremendous help. I'll continue to work on this and update as I make break throughs.


texts: WebGL frame rate slows down after triggering javascript event

texts:
I am using Unity WebGL to host my game on a flask server and trying to throw a warning to the user whenever he tries to navigate away from the tab or mistakenly click browser's back button. Each time after the event is triggered (whenever I try to navigate away) the game slows down with a huge drop in frame rate (navigation has to be performed after the game has been loaded properly by showing the unity logo and other stuffs). Here is the script that I am using to trigger the event:

<script>
    window.addEventListener("beforeunload", function (e)
        {
            var confirmationMessage = "\o/";

            e.returnValue = confirmationMessage;
            return confirmationMessage;
        });
 </script>

What is the work-around of this problem and why the game slows down completely?


texts: How do I unload a scene after doing LoadLevelAdditive?

texts:
I have scene A loaded.

I load scene B with LoadLevelAdditive.

How do I unload scene B and keep scene A loaded?


texts: Rendering tilemaps at a specific position libgdx

texts:
I'm making an endless side scroller game like gravity guy with libgdx.

To test this I'm just creating two tiled maps with the same .tmx file to render then one after another, like:

                            [map1][map2][map3][map4]...

The thing is I'm not succeeding to do this, and I already have searched related problems... I found one topic related with this but I couldn't understand very clearly.

Would be very happy if someone could help me on this!


texts: Night cycle object not going smootly when object instantiated

texts:
Hello so I'm adding night cycle to my game it's going smoothly for object except the instantiated one

as you can see that is a different color on it.
so here the script for night cycle:
 public GameObject ca1, ca2, ca3, ca4, ca5, ca6;

 void Update()
    {
        if (_GameManager.instance.isStarted)
        {
            timer += Time.deltaTime;

            if (timer >= maxTime)
            {
                GenerateObstacle();

                if (_GameManager.instance.score >= 450)
                {
                    if (_GameManager.instance.score % 2 == 0)
                    {
                        GenerateBuwungObstacle();
                    }

                    if (_GameManager.instance.score >= 3000)
                    {
                        if (_GameManager.instance.score % 5 == 0)
                        {
                            GeneratedMeteorObs();
                        }
                    }
                }

                timer = 0;
            }

            if (_GameManager.instance.score % 200 == 0 && activeFade == null && activeFadeObjectClouds == null)
            {

                fadeToBlack = !fadeToBlack;

                Color colorCactusObs = fadeToBlack ? Color.white : Color.gray;

                activeFadeObjectCactus = StartCoroutine(ObjectCactusFadeTo(colorCactusObs));

            }
        }
    }

   // for generating the cactus
  public void GenerateObstacle()
    {
        choosedObstacle = Random.Range(0, Obstacles.Length);
        GameObject obstacle = Instantiate(Obstacles[choosedObstacle]);
    }

  IEnumerator ObjectCactusFadeTo(Color destination)
    {
        Color start1 = ca1.GetComponent<SpriteRenderer>().color;
        Color start2 = ca1.GetComponent<SpriteRenderer>().color;
        Color start3 = ca3.GetComponent<SpriteRenderer>().color;
        Color start4 = ca4.GetComponent<SpriteRenderer>().color;
        Color start5 = ca5.GetComponent<SpriteRenderer>().color;
        Color start6 = ca6.GetComponent<SpriteRenderer>().color;

        for (float t = 0; t < 1f; t += (Time.deltaTime / fadeSpeed) * 2)
        {
            ca1.GetComponent<SpriteRenderer>().color = Color.Lerp(start1, destination, t);
            ca2.GetComponent<SpriteRenderer>().color = Color.Lerp(start2, destination, t);
            ca3.GetComponent<SpriteRenderer>().color = Color.Lerp(start3, destination, t);
            ca4.GetComponent<SpriteRenderer>().color = Color.Lerp(start4, destination, t);
            ca5.GetComponent<SpriteRenderer>().color = Color.Lerp(start5, destination, t);
            ca6.GetComponent<SpriteRenderer>().color = Color.Lerp(start6, destination, t);

            yield return null;
        }

        ca1.GetComponent<SpriteRenderer>().color = destination;
        ca2.GetComponent<SpriteRenderer>().color = destination;
        ca3.GetComponent<SpriteRenderer>().color = destination;
        ca4.GetComponent<SpriteRenderer>().color = destination;
        ca5.GetComponent<SpriteRenderer>().color = destination;
        ca6.GetComponent<SpriteRenderer>().color = destination;

        activeFadeObjectCactus = null;
    }

I already try with for loop in the object cactus fade but still not smooth


texts:
I want to write somewhat randomized object activation effects, like when you step on a trap, you can be tepelorted, damaged, cursed and so on. I applied strategy pattern for this: damage/healing managed by class ChangeHealth, teleportation by class SetPosition etc.

I want to know how can I manage creation of objects in code from data, so, for example I want to be able to set that there will be trap which will damage player and there will be shrine which should teleport you upon activation from, for example, string or bit stream.

I'm working in C#, but interested in overall approach to this problem.


texts: Platformer command queue - not sure how to proceed

texts:
While trying to figure out how to implement platform agnostic input handling for a platformer, I've discovered the command pattern and I liked the idea so I wanted to take it a step further.

I got the idea of having a Command Queue System (I'm using ECS in my gameplay screen/state) which would expose a simple api for enqueueing commands which other systems could invoke and then the command system would execute those commands within a logic loop derived from Fix your timestep blog post.

While processing and implementing this idea, however, I've encountered a couple of issues where I'm not sure on how to proceed:

Input processing is currently done with an abstraction over LibGDX's InputProcessor so input processing is event-driven and thus commands are queued as fast as events are emitted. This in turn causes the queue to fill up the command queue with more and more commands(40-50+) waiting for execution which, along with filling up memory, causes longer and longer delays. I've tried to mitigate this by removing oldest commands from the queue while the queue size is > 10 but that made gameplay really choppy since command removal was on the same thread and is blocking everything else until it's done(at least that's what I'm assuming is going on).
Is a complement to issue 1. wherein if I use a single queue for all commands including all AI NPC's, enemies and the player, I only see massive delays while the systems processes all inbound commands. I could spin up new threads for every entity but then I'm not sure how could I get them to execute within the fixed timestep logic loop, and I'm not particularly fond of having dozens of threads for every single entity.

I really like the idea of having movement and interaction of characters represented as commands but I can't figure out how to implement this without greatly losing precision and performance. Can anyone steer me in the right direction?


texts: Slick2D: Initializing graphics object before game loop

texts: I'm using the Slick2D Java game library and I want to set the scale of the graphics object that gets passed to the render method in my game loop.  I'd like to do this outside the render method, so that I would only have to call the setScale() method once.  I am implementing my game as StateBasedGame, so I'd to like to initialize my graphics object in my StateBasedGame class.  Where would be the appropriate place to do this?


texts: Client side predicition tick implementation

texts: I've been reading about client side prediction and one question I have is what's the best way to implement the server tick. I thought about using the server frame count from the game engine I'm using as an authorative tick, is this advisable due to the changes with delta time or should I just use a simple timer on the server?


texts: How can I compute the orbit of one body around another?

texts:
I'm attempting to have a planet (with a known mass and radius) orbit it's sun (also with a known mass and radius). It doesn't have to be 100% realistic, but it should be possible that the sun have more than one planet orbit it at a time.

What equations should I use to accomplish this?


texts: XNA Subtract blending function doesn't work

texts:
I wanted to subtract a white image with black circle background from a picture to get a lighting circle here is the white image

So I wrote this code

spriteBatch.Begin(SpriteSortMode.Deferred, new BlendState
{
      ColorBlendFunction = BlendFunction.Subtract,
      AlphaBlendFunction = BlendFunction.Subtract
});
//Draw the white image with black circle
spriteBatch.Draw(test, new Vector2(), Color.White);
spriteBatch.End();

I was aiming to get difference between it and the background image rendered

to get something like this

But the result that the first image is only drawn while second is below it


texts: Balancing Player vs. Monsters: Level-Up Curves

texts:
I've written a fair number of games that have RPG-like "levelling up," where the player gains experience for killing monsters/enemies, and eventually, reaches a new level, where their stats increase.

How do you find a balance between player growth, monster strength, and difficulty? The extreme ends of this spectrum are:

Player levels up really fast and blows away monsters without much effort
Monsters are incredibly strong and even at low levels, are very difficult to beat

I've also tried a strange situation of making enemies relative to players, i.e. an enemy will always be at 50% or 100% or 150% of player stats (thus requiring the player to use other techniques instead of brute strength to succeeed).

But where's the balance, and how do you find it?

Edit: For example, I am expecting to hear things like:

Balance high instead of balance low (200 HP and 20 str is easier to balance than 20 HP and 2 str)
Look at easiest vs. hardest monsters, and see what you have in terms of a range


texts: Transform.RotateAround with Joystick Rotation

texts:
I want to rotate one object around another, so that it matches my current joystick rotation. I know Transform.RotateAround does this but I can't seem to find a way to match it with my joystick rotation.

This is my code so far:

void Update()
{
    joystick = InputManager.ActiveDevice;

    moveInput= joystick.RightStickX;

    if(currentState != CoreplayerState.stager) {
        RotateChar();
    }
}

public void RotateChar() {
    transform.RotateAround(target.position, zAxis, moveInput * rotateSpeed);
    transform.rotation = target.rotation;
}


texts: How to make community made levels compatible with every game update, without re-cooking the levels?

texts: Community made maps made in UE4 (BSP & simple assets), downloadable via Steam Workshop, is one of the main features of our hypothetical game. The maps should continue to be compatible regardless of game-updates, without re-cooking each map. Is this possible? Because now it seems every map has to be re-cooked after every game update. However, our hypothetical game can't work like that, considering it has to work with hundreds of community made maps which we can't expect users to re-cook every time.


texts:
I am making a puzzle game in Unity. I have several GameObjects that have children objects where each child object has a BoxCollider2D.

The game requires that the pieces be rotated, but to position them correctly, they also need to be translated under certain rotations. I thought a good way to handle this would be using an animator that has 0, 90, 180 and 270 degree states. When the objects are by themselves, I have this working correctly.

The problem I am having is when there are two adjacent GameObjects. When the user tries to rotate a block and the rotation would result in overlapping colliders, I want to ignore the rotate command and do nothing. Traditionally, this would mean that I would rotate the piece, check collisions, and if there is a collision, rotate back in the same Update() call.

My question is: Is there any way after telling the animation to rotate i.e.

animator.SetFloat("Rotation",animator.GetFloat("Rotation") + 90);

to subsequently tell it to jump to the last frame of the new animation state so that I can check collisions on it and then revert the animation to its original position if there is a collision -- all in the Update() function?

Or am I better off ditching the Animator and doing it myself?


texts: What is the math to project a 3D object's center onto a 2D plane?

texts:
What I really need is the x,y of the object when it is outside of the screen:

I'm actually coding a UI in Objective-C, not a game.
In this different kind of UI you navigate a 3D space with objects.
An observer is at (x=0,y=0,z=0) and objects have realCenter and realSize.
realSize is the size of the objects at z=1.
I have calculated the angular center of the objects to be:
angularCenterX = (objectRealCenter.x - observerCenterX) / distanceFromObserver

Objective-C code:
CGPoint angularCenter = CGPointMake((object.realCenter.x - observer.center.x) / distance,
                                    (object.realCenter.y - observer.center.y) / distance);

It works but when the observer passes the objects, the objects warp around. Instead of disappearing like they normally should, they come back.
The slider controls the z of the observer, as it moves and passes an object the objects comes back:
I'm sorry the gif is too slow.


texts:
Creating interesting, original, logical, thoughtful puzzles is an art.

What techniques and methods do you use to create good puzzles?

Do you write storyline before designing puzzles or combine these 2 processes?


texts:
I'm developing a gameboard for a 4 players cardgame well know in my region ( like a Bridge with 8 cards).

I create a cardcontrol class, all the deck methods and all the logics for value card and score count.

But I need some link or suggestion for the implementation of  "computer player" based on a few rules to follow.

thank you all for any help.


texts: How can I handle intellectual property violations in user-generated content?

texts:
I recently made a simulation game like Gamedev Tycoon where you are in charge of a game company and planning to release it on app stores soon.

I have few questions about trademark and copyright laws, as in game there are different companies (competitor) who release games, make sequels to previous games, release consoles etc. I know that under parody law I can change a company name from MICROSOFT to MICROCRAFT or MINORCRAFT etc. But what if I provide users an editor where they can change company names (if they want to) from MICROCRAFT to MICROSOFT?

Do changes made by players with my editor violate any copyright or trademark law? How can I handle that?


texts: How and when to choose which objects to run collision tests on?

texts:
This might be problem with plenty of good solutions, but it's all not very clear to me, so I though I could ask and probably get some good hints. I'm having trouble figuring out how to handle interaction between objects in a platformer. Basically it's supposed to have two kinds of collision detection: one for solid objects that's based on line tests, and another to detect when ordinary objects touch.

These are some solutions that I know of, but they all have some serious problems:

Store global references to the player and to solid objects, and have all other objects manually detect collisions with them.

Good: trivial to implement, efficient

Bad: limiting, since you can't easily have two non-player objects interact on collision; object implementations are strongly coupled to the player object's implementation
Let objects ask for a list of objects of a certain type, and check for collisions in that list.

Good: simple to use; useful for other things such as finding all solid objects

Bad: I don't know how to implement it nicely (especially in a statically typed language); it requires use of inheritance to classify object types; objects in the same update priority interact slightly differently depending on which one updates first
Let objects send and receive messages, and have a central collision detection system that runs after the update methods and sends messages to all colliding objects.

Good: update order does not matter; object types need to know little, if anything, about each other

Bad: must use the shapes provided by the collision system (no custom tests); most collision tests and messages will be wasted since collisions between most object types are ignored; a separate way to list all solid objects is still needed

So, any suggestions for improvements, alternatives, or good links to read? Suggestions that also simplify related problems like off-screen objects or objects positioned relative to other objects would be appreciated, too.

EDIT: To be clearer, I'm not asking about how to detect a collision given two objects, but about how the two objects can find out about each other in the first place.


texts: How should I handle collectable/droppable/stackable items in an inventory?

texts:
I am working on a game with an inventory system, but am trying to figure out the best way of doing it. I have read the post about adding WorldItems or InventoryItems to a list, which is fair enough and I figured that out myself anyway.

However, perhaps I add two SwordItems to this list (for example). I want the game to show that I have quantity 2 of these, not two individual items. What is the best way to achieve this with a List based inventory structure. I think I saw a GroupBy method, where I could GroupBy item type Sword. Is this a good way to achieve this? Or can you suggest a better alternative?


texts:
I have some experience with Blender, but now I am using Xcode 9.2 and OpenGL 4.1 on MacBook Pro. I am also attending a couple of online courses on edX.

I am developing (for fun and as an exercise) a very simple FPS game. I haven't handled collisions, yet, and I am thinking of how to implement projectiles.The question I have about projectiles, when they are actual object and several of them are present simultaneously in the scene, is the following. Is it better, performance-wise, to generate an object for each active projectile or simply reuse the same object but redrawing it several times and with different transformation matrix (passed to the same shader via uniform mat4)?


texts: How to check if a variable is an integer?

texts:
I'm going through my C++ book and have currently made a working Guess The Number game.

The game generates a random number based on current time, has the user input their guess, and then tells them whether it was too high, too low, or the correct number.

The game functions fine if you enter a number, but returns 'Too High' if you enter something that is not a number (such as a letter or punctuation). Not only does it return 'too high', but it also continually returns it.

I was wondering what I could do to check if the guess, as input by the user, is an integer and if it is not, to return 'Not a number. Guess again.'

Here is the code.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(time(0)); // seed the random number generator
    int theNumber = rand() % 100 + 1; // random number between 1 and 100
    int tries = 0, guess;

    cout << "\tWelcome to Guess My Number!\n\n";

    do
    {
        cout << "Enter a guess: ";
        cin >> guess;
        ++tries;

        if (guess > theNumber)
                cout << "Too high!\n\n";

        if (guess < theNumber)
                cout << "Too low!\n\n";

    } while (guess != theNumber);

    cout << "\nThat's it! You got it in " << tries << " guesses!\n";
    cout << "\nPress Enter to exit.\n";

    cin.ignore(cin.rdbuf()->in_avail() + 1);
    return 0;
}


texts: Unity rotating camera around specific Vector

texts:
I'm making a game in which the player controlls a ball. (Wow, such originality^^)
It's a 3rd person game so the camera is slightly above and behind it.
The ball is being controlled via WASD.
Now the tricky part is, I want this to work totally independent from the worldaxis so or example even upside down. So in my PlayerControllerScript I have an array of three vectors which represent the new X,Y and Z axis of my ball. The X axis always points in the direction the sphere is moving. The Y axis is calculated by the forces influencing the body.
So if the gforces on the body are strong enough, for example while rolling along a craterslope, my Y axis is going to be horizontal.
The Z axis is always orthogonal to the firs two.

So much for the explanation. So the camera is always being offset according to those new axis' and then pointed in direction of the gameobject using this line:

T.rotation = Quaternion.LookRotation (TargetTrans.position - T.position);

T being the Camera's transform. I don't really understand this line but it works. My problem is, that this makes the camera always parallel to the horizon, but I want the camera to tilt with the objects movement. So when I'm rolling in circles on a craterslope it should not be parallel to the horizon but to the slope.
I tried to Rotate the Transform of the camera around the calculated X axis like so:

T.Rotate(PlayerScript.Orientation[0] , Vector3.Angle(Vector3.ProjectOnPlane( Physics.gravity,PlayerScript.Orientation[0]) ,OtherScript.Orientation[1])   );

Notice that I'm taking the angle between my calculated Y axis and the gravity beeing projected onto the YZ Plane of y calculated orientation. Like this I avoid unwanted tilting, for example when moving straight up the crater slope away from the center.
However this line doesn't change anything visually. What's wrong? It's not because the rotation is changed right afterwards with the first command I gave, because the Rotate command comes after it.

I'm starting to realize rotation is a lot more complicated than I thought and eventhough this has to be a very common problem in for all peple who develop games with planes, I couldn't find anything. :(

Help me please...
Thanks in advance.

I also realize how hard this even is to explain so let me know if something is not clear.


texts:
I'm having a small issue with libgdx animation.

I'm using getKeyFrame() to get the current frame of the animation and I'm updating the state time by adding on deltaTime in my update function for the object. The animation is not looping.

My problem is that the animation seems to play at different speeds depending on the frame rate. On my phone this animation plays particularly slow. My thinking was that the stateTime would cause it to skip a few frames when it's going slow, but this doesn't seem to be happening.

Here is the code;

        sprite = Animation.getKeyFrame(stateTime, false);
        sprite.setRotation(angle);
        sprite.setPosition(position.x, position.y);
        sprite.draw(batch);

Has anyone else experience this issue.


texts: In JavaScript, should I write a game loop for a turn-based game?

texts:
I am using javascript and HTML5 canvas for turn-based games (e.g., checkers, mastermind, minesweeper).

Should I write a fixed-timestep game loop? What are the alternatives?


texts: How to draw sprite according to Player position when button is pressed?

texts:
How do I draw a sprite right at my Player sprite's position when I pressed Spacebar?

protected void playerInput() {
        KeyboardState key = Keyboard.GetState();

        if (key.IsKeyDown(Keys.Escape)) this.Exit();
        if (key.IsKeyDown(Keys.Up))     playerPos.Y -= 5;
        if (key.IsKeyDown(Keys.Down))   playerPos.Y += 5;
        if (key.IsKeyDown(Keys.Left))   playerPos.X -= 5;
        if (key.IsKeyDown(Keys.Right))  playerPos.X += 5;
        if (key.IsKeyDown(Keys.Space))  bSpawnSandbag = true;
    }

protected override void Update(GameTime gameTime) {
        playerInput();
        base.Update(gameTime);
    }

 protected override void Draw(GameTime gameTime) {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(player, playerPos, Color.White);

        if (bSpawnSandbag) {
           spriteBatch.Draw(sandbag, new Vector2(playerPos.X + 3, playerPos.Y + 3), Color.White);
        }

        spriteBatch.End();

        base.Draw(gameTime);
    }

If I use the code above, the "sandbag / the sprite I want to draw" will move with my Player position and I don't want that. I want it to draw at THAT specific position my Player was once at when I press Spacebar for 1 time. Any clue? O_O
I want it to be...

Let say, player position = (10, 10) Player pressed Spacebar, draw Sandbag at 10,10 (permanently) Even though Player moved to 12, 10 & not pressing Spacebar , the Sandbag would still be at 10,10


texts: Unity3d Rigidbody movement along slope slowdown

texts:
I have a Rigidbody character controller (Unity, C#) which I'm trying to make work seamlessly when walking on sloped ground. I've got it working fine walking up and down a slope by changing the forward direction to always be parallel to the ground (using the surface normal). But a strange thing is happening when walking sideways on that same slope (and not up and down it)...the character slows to a crawl. Anyone have any idea why this might happen, or how to solve it?
private void Walk()
{
    isMoving = false;

    if (!inChatwithNpc && !ledgeChecker.isGrabbingLedge)
    {

        isMoving = true;

        playerRigidbody.AddForce(moveDirection * moveSpeed /** multiplier*/ * Time.deltaTime);

        if (playerOnGround)
        {
            playerRigidbody.velocity = Vector3.Lerp(playerRigidbody.velocity, moveDirection * playerRigidbody.velocity.magnitude, Time.deltaTime / 0.5f);

            if (!isRunning)
            {
                playerRigidbody.velocity = Vector3.ClampMagnitude(moveDirection * playerRigidbody.velocity.magnitude, 12f);
            }

            if (isRunning)
            {
                playerRigidbody.velocity = Vector3.ClampMagnitude(moveDirection * playerRigidbody.velocity.magnitude, 18f);
            }
        }

    }

    if(!isMoving && playerOnGround)
    {
        playerRigidbody.velocity = Vector3.Lerp(playerRigidbody.velocity, Vector3.zero, 0.2f);
    }
}
private void CalculateForward()
{
    if (!playerOnGround)
    {
        forward = transform.forward;
        return;
    }

    forward = Vector3.Cross(transform.right, touch.normal);


texts: Frustum Culling behaves incorrectly with vertex shaded objects

texts:
I have a scene with a straight path. It looks something like this:

I've also wrote a vertex shader that bends the path. After applying the shader, it looks something like this:

If you were to look at the walls on the right, the emptiness is created by wall tiles that were culled by the camera's default frustum culling.

Is there a way fix this without disabling frustum culling completely?


texts: Rotate Rigidbody2d slowly for 360 degrees

texts:
I would like to perform a 360 degree rotation on a GameObject with rigidbody2d component. You should be able to see the rotation, so I thought of rotating the object 8 times with 45 degrees each around the z axis. So far, one might think that this should be an easy task. But, after several hours, I'm really stuck here.

I tried several code snippets (although not understanding them completely, I must admit):

void FixedUpdate()
{
    rigidbodyComponent.MoveRotation(45.0f);
}

==> Rotates the object one time for the desired angle.

void FixedUpdate()
{
   rigidbodyComponent.MoveRotation(45.0f);
}

==> Nothing happens.

Could you please give my a hint in what direction (meaning: classes / methods) I should proceed?

Thanks.


texts: How to Get VR Controller's Velocity in Unity with SteamVR?

texts:
Back when I used Unity 2017 and controller bindings weren't a thing, I simply attached a rigidbody to my Vive controller and read out the velocity of the rigidbody to know how fast the player was swinging the controller. Now, I've updated to Unity 2021.2.0a14, I went through all the effort of modifying my code to work with bindings, and it doesn't seem like I can get velocity anymore. The rigidbody always reports zero velocity. I can see the World Center of Mass vector changing so I know it registers motion, but it's just not reporting the velocity anymore. Is there a new setting in Unity I need to turn on to measure things that it doesn't personally control? Or do the new bindings options have a way to get velocity as an input? Am I forced to calculate it myself now? Thanks!
Edit: Base assumption was wrong, I did not get velocity from the rigidbody attached to the hand controller like I thought I did. I got it directly from SteamVR_Controller. So Unity is probably acting like it ever did.


texts: Tracking launch errors for your game with a simple c++ app

texts:
I am trying to create a simple app to track launch errors for my game. The idea is to launch a c++ program, that in turn launches the main game .EXE file with CreateProcess(). The c++ app then proceeds to wait untill the process finishes and shows an error report to the user, if the error happened. This is how I implemented this:

#include <windows.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{
    // additional information
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    // set the size of the structures
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    const string appName = "MAIN.exe";
    const string appLocation = "";

    // start the program up
    BOOL result = CreateProcess((appLocation + appName).c_str(),   // the path ".." <- перейти вверх "\\" <- относительный путь.
        NULL,        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to si structure
        &pi);           // Pointer to PROCESS_INFORMATION structure

    if (!result)
    {
        MessageBox(HWND_DESKTOP, ("Could not locate " + appName + "! Please reinstall the game!").c_str(), "Error!", MB_OK);

        // We failed.
        return FALSE;
    }
    else
    {
        // Successfully created the process.  Wait for it to finish.
        WaitForSingleObject(pi.hProcess, INFINITE);

        DWORD exitCode = NULL;
        // Get the exit code.
        result = GetExitCodeProcess(pi.hProcess, &exitCode);

        // Close process and thread handles.
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);

        if (!result)
        {
            // Could not get exit code.
            MessageBox(HWND_DESKTOP, "ERROR!", "Error!", MB_OK);
            return FALSE;
        }
        else if (exitCode != 259 && exitCode != 2)
        {
            if (exitCode == 1)
                MessageBox(HWND_DESKTOP, "ERROR!", "Error!", MB_OK);
            else
            {
                string errorString = to_string(exitCode);
                LPCSTR errorText = errorString.c_str();
                MessageBox(HWND_DESKTOP, errorText, "Launch error!", MB_OK);
            }
        }

        // We succeeded.
        return TRUE;
    }

    //MessageBox(HWND_DESKTOP, "Text here", "Text here", MB_OK);
    return 0;
}

From my humble tests I did not see any performance decrease, however, the c++ process is constantly sitting in the background and I wonder if there might be any problems with I that I should know about. Maybe there is a safer/easier way to implement this?

UPDATE: Just to clarify here are the reasons why I need this app (alongside trying to track errors internaly, which I already do):

I am developing on c# and XNA 4.0 for .Net Framework 4.5.1. And just that setup can lead to several issues:

1)The user might not have XNA 4.0 redist installed;

2)The user might have Windows 7 with vanila .Net 4.0 and not 4.5.1;

3)The user might have Windows XP which I do not support (due to .Net target 4.5.1);

4)The user might have a GPU which does not support DX 10, (a requirenment for XNA 4.0).

But in most of those cases the app will simply crash on startup, and from what I read, there is no way to catch an error internaly as they happen at an assembly level.


texts:
With all the recent interest in developing HTML5 apps and games, and I am curious why all the focus is on Javascript, and not on Java.

Minecraft is a great example of what can be accomplished in a browser, and it's written in Java, not JS. I doubt if it is even possible/practical to attempt such a complex project in JS.

Java is clearly a more powerful platform, and it probably runs significantly faster (this is just my guess, though). About the only drawback of Java I can think of is that it runs as a plugin, and with the trend towards plugin-free browsers (e.g. IE10 metro) Java applets may become obsolete in mobile environments. This has already happened with Flash on iOS.

What do you think? Is there a future in developing Java-based Web apps (especially for mobile devices)?

Thanks


texts:
Unity Version: 2019.4.1f1
Render Pipeline: URP
I created a shader using Unity's ShaderGraph, and i want to apply GPU Instancing on this shader, but there is no way to declare per-instance properties inside the shader graph.
Is there a way to make GPU Instancing work on shader graphs' materials?


texts: How to convert pixels to meters in Box2d with Cocos2d-x 3.5?

texts:
I am using Cocos2d-x 3.5. I created a simple game with edge bodies and one circular body to test box2d. Physics wasn't working well, so i thought i should convert pixels to meters and use that meters for example on aplying impulses.

I don't know how to do it. I can't find any converting function. Also there is no any PTM_RATIO variable. I tried to create it myself, but i don't really know how to use it properly. Can you help me please to understand that?
Thank you.


texts: When using transformation matrices, how does one convert orientation and scaling from a global frame of reference into a local one?

texts:
Note: I'm certain I cannot be the first to answer this question. Unfortunately, the answers I need are buried under an avalanche of posts asking how to move coordinates between frames of reference, and other similar but unhelpful problems.
As part of an ongoing project, I've built a Transform object. As one might expect, this is essentially a glorified wrapper around a 4x4 transformation matrix (and various base values), and provides abstracted ways of interacting with position, orientation, and scale, as well as handling parenting to other instances to build complex hierarchies.
I am currently trying to allow the user to set and alter values of child transforms in global terms. Position is straightforward (if I'm doing it right), as this simply involves converting a coordinate from a global frame or reference to a local one.
void Transform::setGlobalPosition(const glm::vec3& newPos)
{
    glm::vec4 nlp = glm::vec4(newPos, 1.0f);
    if (m_hasParent) {
        // This gets the parent transform from the Entity-Component System.
        auto& p = p_registry->get<Transform>(m_parent);

        nlp = glm::inverse(p.m_globalTransformM) * nlp;
    }

    setPosition(nlp);
}

void Transform::alterGlobalPosition(const glm::vec3& deltaPos)
{
    glm::vec4 nlp = glm::vec4(m_globalPosition + deltaPos, 1.0f);
    if (m_hasParent) {
        // This gets the parent transform from the Entity-Component System.
        auto& p = p_registry->get<Transform>(m_parent);

        nlp = glm::inverse(p.m_globalTransformM) * nlp;
    }
        setPosition(nlp);
}

However, I have absolutely no clue how to accomplish the same for the following.
// Transform member functions.
void setGlobalScale(const glm::vec3& newScale);
void alterGlobalScale(const glm::vec3& deltaScale);
void setGlobalOrientation(const glm::quat& newOri);
void alterGlobalOrientation(const glm::quat& deltaOri);

Position coordinates are easy, but how does one approach the problem for rotations and scaling? Any help would be greatly appreciated.


texts:
I seem to recall Unity's Random is automatically seeded; checking the documentation it doesn't say it outright, but a certain interpretation of their words might seem to imply it.

  The seed is normally set from some arbitrary value like the system
  clock before the random number functions are used. This prevents the
  same run of values from occurring each time a game is played and thus
  avoids predictable gameplay. However, it is sometimes useful to
  produce the same run of pseudo-random values on demand by setting the
  seed yourself.

(emphasis added)


texts: Why use Time.deltaTime in Lerping functions?

texts:
To my understanding, a Lerp function interpolates between two values (a and b) using a third value (t) between 0 and 1. At t = 0, the value a is returned, at t = 1, the value b is returned. At 0.5 the value halfway between a and b is returned.

(The following picture is a smoothstep, usually a cubic interpolation)

I have been browsing the forums and on this answer I found the following line of code: transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation, Time.deltaTime);

I thought to myself, "what a fool, he has no idea" but since it had 40+ upvotes I gave it a try and sure enough, it worked!

float t = Time.deltaTime;
transform.rotation = Quaternion.Slerp(transform.rotation, toRotation, t);
Debug.Log(t);

I got random values between 0.01 and 0.02 for t. Shouldn't the function interpolate accordingly? Why do these values stack? What is it about lerp that I do not understand?


texts:
I need a map file structure for my game but does anyone know a good way to map it out? I was thinking something like this:

name=MyMap
add[floor[stone]][solid][20, 640]
add[playerspawn][20, 620]


texts: Steering behaviors: how to flee then go back towards the hunter?

texts:
I have implemented a Wander and Flee steering behavior and it works like this:

When the entity is not hunted by anything it wanders around. But when it is hunted by the player it will flee away from the player at growing speed. This is like a butterfly that flees quickly.

But now I want to change its behavior. So that when the entity is hunted by the player, it flees away at the beginning. But if the player keeps chasing the entity it will go back towards the player at a slower speed so that the player can catch the entity. In my previous implementation the player cannot catch the entity because the entity always has a fleeing force if the player comes closer.

Can I just decrease the fleeing force over time? But this still cannot guarantee the entity is catchable and it will make player feel the entity is not moving.


texts:
I am just trying to create a movementcontroller class for game entities. These class should  transform the entity affected by the mouse and keyboard input. I am able to calculate the changed rotation and the new globalPosition. Then I multiply:

 newGlobalMatrix = changedRotationMatrix * oldGlobalMatrix;
 newGlobalMatrix = MatrixSetPosition(newPosition);

The problem is that the object rotates around the global axis and not around the local axis.

I use XNAMath for the matrix calculation.


texts: How to program smooth player 2D movements

texts:
I am writing a simple 2D game in Rust, having access to the following dependencies:

Piston: for the graphic engine
nphysics: for the physics engine

The genre is Metroidvania, the game features a single map Super Mario style, where the player can only move backwards and forwards and jump (and throw attacks). Modern games, such as Hollow Knight just to give an example, allow the player the same type of movements and they are very smooth.

I have never developed a game with these features, and from my first attempts now it looks like developing these smooth movements is harder than I thought it would be.

I have thought of several alternatives in order to move the player, but I am not sure which of these approaches is the best one or if there are others that are even better:

Do not rely on the physics engine at all and implement the movements just by changing the position of the graphics (shapes/sprites...). I personally didn't try this one because it sounds like a lot of work that does not guarantee good results.
Implement the movements by setting the velocity of the player through the physics engine.
Implement the movements by applying a force to the player through the physics engine.

I guess the answer would also depend on how to handle the user inputs properly and link them to the player movements, since they are very strictly related to each other.


texts: How do I rotate a segment + normal so that the normal is (0,-1) and the segment is now axis aligned

texts:
I have an arbitrary line segment, which may or may not be axis aligned along with its normal
eg: Segment(Coord(-1,-1), Coord(1,1), Coord(-1, 1).normalize) which represents a line segment with a 45 degree angle.

My desire is to transform that line to Segment(a:Coord, b:Coord, Coord(0,1))

I have a beginners understanding of how transformation matrixes work, in that I know I can get a rotation matrix and apply it to each of the Coords and I'll be left with my segment in the coordinate space I want.

I do not however, know how to calculate that rotation matrix given I know the start normal and the desired end normal.


texts: Random numbers with a left or right biased skew

texts:
Within Java I have a table of objects ranging from horrible (1%) to wonderful (100%) from which one is randomly selected. This is simple enough and appears on a bell curve with a normal distribution and the average at the 50% mark. But at various stages I wish for this distribution to shift left or right meaning that you are more likely to generate a less pleasant item or at other stages, generate a more pleasant one. The table ranges from 1 to 100.

How do I generate a random number that is biased to one end of the table and not the other, while still being able to, in this case in a bad situation, randomly come up with a 100%? I have looked at Random.nextGaussian(). But this doesn't seem to quite do it, if I am reading it correctly.


texts: How do I make an on-screen HUD in libgdx?

texts:
I'm new to libgdx, and I am finding I am getting stumped by the simplest of things.  It seems to want me to do things a specific way, but the documentation won't tell me what that is.

I want to make a very simple 2d game in which the player controls a spaceship.  The mouse wheel will zoom in and out, and information and controls are displayed on the screen.

But I can't seem to make the mouse wheel NOT zoom the UI.  I've tried futzing with the projection matrices in between

Here's my (current) code:

public class PlayStage extends Stage {
...
    public void draw() {
    // tell the camera to update its matrices.
    camera.update();

    // tell the SpriteBatch to render in the
    // coordinate system specified by the camera.
    spriteBatch.setProjectionMatrix(camera.combined);

    spriteBatch.begin();

    aButton.draw(spriteBatch, 1F);

    playerShip.draw(spriteBatch, 1F);

    spriteBatch.end();
}
}

camera.zoom is set by scrolled(int amount).

I've tried about a dozen variations on the theme of changing the camera's projection matrix after the button is drawn but before the ship is, but no matter what I do, the same things happen to both the button and the ship.  So:

What is the usual libgdx way of implementing an on-screen UI that isn't transformed by the camera's projection matrix/zoom?


texts: smallest distance randomly generated objects

texts:
For a project in gamemaker, I'm making a galaxy with several planets in it (about 30), which have random placements (there is a minimum distance between them).
After the planet generating, i'm trying to figure out how to calculate the two closest planets for each individual planet, so I can make trade routes between them.
So, each planet has two planets that are closest to it, and I'm trying to make an array in which the coordinates of that planet and the two closest planets are.

I'm using the following code:

///trade route making
var a1;
var a2;
var R1;
var dist;

//what each kolom is
global.traderoutes[0,0]="x1";
global.traderoutes[1,0]="y1";
global.traderoutes[2,0]="x2";
global.traderoutes[3,0]="y2";

//global.traderoutes coordinates length, +1 everytime a set is added
global.R1=1;

for (i=1;i=global.TT;i+=1){

  global.a1=100000000; //a1 and a2 are values to check against, larger than any distance could possibly be.
  global.a2=100000000;
for (j=1+i;j=global.TT;j+=1){
    dist=point_distance(global.planetinfo[1,i],global.planetinfo[2,i],global.planetinfo[1,j],global.planetinfo[2,j]);
    if (dist<=global.a1){
       global.traderoutes[0,R1]=global.planetinfo[1,i];
       global.traderoutes[1,R1]=global.planetinfo[2,i];
       global.traderoutes[2,R1]=global.planetinfo[1,j];
       global.traderoutes[3,R1]=global.planetinfo[2,j];

       global.a1=dist;
       global.R1+=1;
    }
    else if (dist<=global.a2){
       global.traderoutes[0,R1]=global.planetinfo[1,i];
       global.traderoutes[1,R1]=global.planetinfo[2,i];
       global.traderoutes[2,R1]=global.planetinfo[1,j];
       global.traderoutes[3,R1]=global.planetinfo[2,j];

       global.a2=dist;
       global.R1+=1;
    }
}
}

global.TT is the length of the planetinfo array, where all the coordinates for each planet are stored in the first (xcoordinate) and second(ycoordinate) column.

However, it doesn't work. global.traderoutes always comes out empty, it doesn't create any new rows beside the 0th one, where "x1, y1,x2,y2" are written above each kolomn.
Can anyone see a mistake I made in the code? Any help would be greatly appreciated.


texts: How do I use createPattern with a spritesheet?

texts:
Say that I have a spritesheet like this

And I want to use the dirt tile at (1, 1). I know that I can repeat an entire image using createPattern but how do I create the pattern from just the tile section of the image? So far I have this

var pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(x, y, w, h);

I know I could use repeated calls to ctx.drawImage but is it possible to get the same effect using patterns?


texts: Copying render target texture loses all depth

texts:
I have a render target RenderTargetScene that holds my scene texture with the scene's depth buffer

            rtScene = new RenderTarget2D(
            graphicsDevice,
            graphicsDevice.PresentationParameters.BackBufferWidth,
            graphicsDevice.PresentationParameters.BackBufferHeight,
            false,
            SurfaceFormat.Rgba64,
            DepthFormat.Depth24Stencil8, // Requires a depth format for objects
              // to be drawn correctly (e.g. wireframe model surrounding model)
            0,
            RenderTargetUsage.PreserveContents
            );

If I attempt to copy the render target contents to another render target using the following code

        game.GraphicsDevice.SetRenderTargets(sceneCopy);

        game.GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0f, 0);
        //game.GraphicsDevice.Clear(Color.Transparent);

        game.SpriteBatch.Begin(
            SpriteSortMode.Immediate,
            BlendState.Opaque,
            SamplerState.PointClamp,
            DepthStencilState.Default,
            RasterizerState.CullCounterClockwise
            );

        game.SpriteBatch.Draw(game.RenderTargetScene,
             new Rectangle(0, 0, sceneCopy.Width, sceneCopy.Height), Color.White);

        game.SpriteBatch.End();

Then the texture is copied across but the depth buffer appears to be lost.

This is apparent when using DepthStencilState.DepthRead as there is no depth for the objects drawn with that render state to read.

How can I make sure the depth buffer is copied across too?

EDIT:

I have a depth texture created via my deferred rendering system so I thought I would use that.

I'm now drawing a full screen quadrangle using a depth writing shader

    public void RestoreDepthBuffer(Texture2D depthTexture)
    {
        // Set the render states
        game.GraphicsDevice.BlendState = BlendState.Opaque;
        game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        game.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
        game.GraphicsDevice.SamplerStates[0] = SamplerState.PointClamp;

        Effect effect = restoreDepthBuffer;

        effect.CurrentTechnique = effect.Techniques["Default"];

        effect.Parameters["DepthTexture"].SetValue(depthTexture);

        effect.CurrentTechnique.Passes[0].Apply();

        game.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
            PrimitiveType.TriangleStrip,
            NearPlaneVerticesVPT,
            0,
            4,
            Indices,
            0,
            2
            );
    }

The important parts of the shader look like

struct PixelShaderOutput
{
   float4 Colour                        : COLOR0;
   float Depth                          : DEPTH;
};

PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
{
    PixelShaderOutput output;

    output.Colour = float4(0, 0, 0, 0);
    output.Depth = 1.0f - tex2D(DepthSampler, input.TextureCoordinates).r;

    return output;
}

This is still not working though.

EDIT2:  I've got it to work but I have to set the depth and draw all the objects when the RenderTarget is first set and not unset it again.

Should I post an answer based on my working method?


texts: Multipart character sprite and transparency

texts:
In my 2D platform game I have characters made of multiple separate pieces that can move independently in a hierarchy, so that I could move the limbs and head, change facial expressions etc., or add equipment or weapons they carry.

The problem is that when I make the character semi-transparent (like a ghost, or an "invisibility spell") by making the entire hierarchy transparent, their layering starts to be visible and the parts that has been hidden behind others suddenly start to be seen through other body parts :P (e.g. its body hidden behind clothes, or parts of the legs that are inside the body).

I would rather want the entire image of the character to become transparent, as a whole. (The way the character is built from separate sprites is an "implementation detail" that shouldn't be visible to the player, especially if it looks ugly :P )

Any ideas how could this be achieved?

I had an idea that I could first render the entire character into a texture and then display a simple rectangle with that texture applied, but that would probably complicate the rendering pipeline a lot, because it would require multiple stages before the character ultimately appears on the screen, and all of that for every character that would have to be rendered with transparency. So although it would probably work, I don't think it is the best idea. Are there any better ways to do it?

Side note: I want my characters to be customizable by the players, so that they could choose the skin colour, clothes, weapons & stuff. So I figured that I could make a base model in grey scale and then colourize it by changing the colour of the underlying mesh (kinda like those cheap lighting effects from the old days) or the texture mixing. But that of course requires some layering of all the component pieces of the character (e.g. outline and fill being separate, and interleaved for limbs and body so that the outlines were always underneath all the fill layers).
But this causes the same problem with transparency, because then the outlines might be seen through the fills. But I guess that if the transparency problem will be solved, this problem will go away too.


texts: Why my dynamically generated Sprites overlap?

texts:
I'm trying to dynamically generate scene representing chess board made from sprites. I'm using two textures for these:
 - pieces.png (taken from here: http://opengameart.org/sites/default/files/chess_2.png)
 - tiles.png (drawn by hand, consists of two 128x128 squares filled with different colors)

The best result I achieved so far is a board with overlapping tiles:

The sprite mode for these textures is "Single" and pixels per unit are set to "128" (unsure whether I should've done this or not)

The textures are being sliced to sprites in my MonoBehavior.Start:

            var tiles = new Dictionary<int, Tile> ();
            var sprites = new Dictionary<int, Sprite> ();

            // Load all tilesets
            foreach (var externalTileset in map.tilesets) {
                    var tilesetAsset = (TextAsset)Resources.Load ("Boards/" + externalTileset.source);
                    var tileset = (Tileset)tilesetSerializer.Deserialize (new StringReader (tilesetAsset.text));

                    Texture2D texture = (Texture2D)Resources.Load ("Boards/" + tileset.image.source.Replace (".png", ""), typeof(Texture2D));
                    Debug.Log ("Texture for " + tileset.image.source + " loaded: " + texture.width + 'x' + texture.height);

                    int tilesPerRow = tileset.image.width / tileset.tilewidth;
                    int totalTiles = (tileset.image.width / tileset.tilewidth) * (tileset.image.height / tileset.tileheight);
                    for (int tileId = 0; tileId < totalTiles; tileId++) {
                            float x = tileset.tilewidth * (tileId % tilesPerRow);
                            float y = (tileId / tilesPerRow + 1) * tileset.tileheight;
                            sprites [externalTileset.firstgid + tileId] = Sprite.Create (texture, new Rect (x, texture.height - y, tileset.tilewidth, tileset.tileheight), new Vector2 (0.5f, 0.5f));
                    }

                    if (tileset.tiles != null) {
                            foreach (var tile in tileset.tiles) {
                                    tiles.Add (externalTileset.firstgid + tile.id, tile);
                            }
                    }
            }

And when sprites are added to newly created game objects:

        float minX = -4;
        float maxX = 4;
        float minY = -4;
        float maxY = 4;

        for (int i = 0; i < map.height; i++) {
                float y = minY + i * (maxY - minY) / map.height;
                for (int j = 0; j < map.width; j++) {
                        float x = minX + j * (maxX - minX) / map.height;
                        if (pieces [i, j] != null) {
                                GameObject piece = new GameObject (pieces [i, j].properties ["Color"] + ' ' + pieces [i, j].properties ["Type"]);
                                SpriteRenderer renderer = piece.AddComponent<SpriteRenderer> ();
                                renderer.sprite = piecesSprites [i, j];
                                piece.transform.position = new Vector2 (x, y);

                        }
                        if (tileSprites [i, j] != null) {
                                GameObject tile = new GameObject ("Tile");
                                SpriteRenderer renderer = tile.AddComponent<SpriteRenderer> ();
                                renderer.sprite = tileSprites [i, j];
                                tile.transform.position = new Vector2 (x, y);
                        }
                }
        }

I believe I can hack something to make this work, but I want to know how to do it properly
What's wrong with my code or scene/resources setup?


texts: floating health bar above gameObject for 2D mobile game

texts:
I know it's been asked a lot but I can't find the best solution for mine  this whole day. I'm new in programming, so I have a health bar which is a child of my character which is position above it.  My script is working but not the way I want it to. the local position is not decreasing as the health does and the scales size is bigger. Now I have tried several tweeks but I just could not figure it out.

Here is my code attached on the healthbar object :

 Vector3 mylocalScale;

void Start() {

    mylocalScale = transform.localScale;
}

void Update() {
    mylocalScale.x = PlayerHealthSystem.PHS.P_Health;
    transform.localScale = mylocalScale;
}

this is the current health bar behaviour on how it it decreases which is not I want.

my desired result it should decrease from left to right, can anyone help me to do this and understand how to do it? thanks.


texts:
How do I handle resolution change in OpenGL and SDL2, in combination?

Let´s assume I have a GUI window with a fixed position, so it will be on the right corner of the window, and after resolution change it will be at the same position, just resized due to the resolution change. How do I handle the resolution change?

How do I apply these changes to my game physics? For example, with collision boxes, do I need to define some variable like resolutionRatio and multiply it against the collision rectangle dimensions?


texts: 2D - Need help understanding how to resolve multiple collisions in a simple physics engine

texts:
I am trying to create a small game engine in Java using only basic openGL functions and implementing everything else from scratch.

I am trying to get a basic physics engine working (similar to box2D only much simpler), I managed to detect collisions between my different bodies using SAT and I followed this tutorial to try and implement collision resolution.

It seems to be somewhat working but there are still some issues left. The biggest one is that when I have multiple objects colliding they seem to be sinking into each other (however everything works fine with only two objects).
Here's an example demonstrating what I'm talking about:

Here is my code used to resolve collisions:

    /**
 * Resolves the collision
 */
public void         resolve()
{
    TekRigidBody    bodyA;
    TekRigidBody    bodyB;
    TekVector2f     rv;
    TekVector2f     impulse;
    TekVector2f     correction;
    float           normalVelocity;
    float           massSum;
    float           ratio;
    float           e;
    float           j;

    bodyA = collider1.gameObject.getBehavior(TekRigidBody.class);
    bodyB = collider2.gameObject.getBehavior(TekRigidBody.class);
    if (bodyA == null || bodyB == null || (bodyA.getInvMass() == 0f && bodyB.getInvMass() == 0f))
        return ;
    rv = TekVector2f.sub(bodyB.velocity, bodyA.velocity);
    normalVelocity = rv.dot(normal);
    if (normalVelocity > 0)
        return ;
    e = Float.min(bodyA.material.restitution, bodyB.material.restitution);
    j = -(1 + e) * normalVelocity;
    j /= bodyA.getInvMass() + bodyB.getInvMass();
    impulse = TekVector2f.scale(normal, j);
    bodyA.velocity.sub(TekVector2f.scale(impulse, bodyA.getInvMass()));
    bodyB.velocity.add(TekVector2f.scale(impulse, bodyB.getInvMass()));
    correction = TekVector2f.scale(normal, Float.max(penetrationDepth - 0.001f, 0.0f)/ (bodyA.getInvMass() + bodyB.getInvMass()) * 0.8f);
    bodyA.transform.position.sub(TekVector2f.scale(correction, bodyA.getInvMass()));
    bodyB.transform.position.sub(TekVector2f.scale(correction, bodyB.getInvMass()));
}

Edit: Updated code to make it easier to read


texts: How to detect a collision between a isosceles trapezoid and a circle

texts:
I figured one approach would be to divide the trapezoid in three parts, two triangles and a rectangle in the middle.

Then for the circle-rectangle case I would check collision like this:

function testCircleRectCollision(circle, rect) {
    closestX = clamp(circle.x, rect.left, rect.right)
    closestY = clamp(circle.y, rect.top, rect.bottom)

    distanceX = circle.x - closestX
    distanceY = circle.y - closestY

    return pow(distanceX, 2) + pow(distanceY, 2) < pow(circle.radius, 2)
}

For the circle-trangle case, I could only think of checking if the vertices of the triangle are inside the circle like this:

function vertexInCircle(circle, v) {
    return pow(v.x - circle.x, 2) + pow(v.y - circle.y, 2) < pow(circle.radius, 2)
}

But I still need to check two cases: 1) if the circle is completely inside the rectangle and 2) if the circle is intersecting with any of the triangle's edges. How can I do this?

Or is there a better way to check for circle-trapezoid collision?


texts: Drawing a texture at the end of a trace (crosshair?) UDK

texts:
I'm trying to draw a crosshair at the end of my trace.

If my crosshair does not hit a pawn or static mesh (ex, just a skybox) then the crosshair stays locked on a certain point at that actor - I want to say its origin.

Ex: Run across a pawn, then it turns yellow and stays on that pawn. If it runs across the skybox, then it stays at one point on the box. Weird?

How can I get my crosshair to stay consistent? I've included two images for reference, to help illustrate.

Note: The wrench is actually my crosshair. The "X" is just a debug crosshair. Ignore that.
/// Image 1 ///
/// Image 2 ///

/***************************************************************************
* Draws the crosshair
***************************************************************************/
function bool CheckCrosshairOnFriendly()
{
local float             CrosshairSize;
local vector            HitLocation, HitNormal, StartTrace, EndTrace, ScreenPos;
local actor             HitActor;
local MyWeapon          W;
local Pawn              MyPawnOwner;

/** Sets the PawnOwner */
MyPawnOwner = Pawn(PlayerOwner.ViewTarget);
/** Sets the Weapon */
W = MyWeapon(MyPawnOwner.Weapon);

/** If we don't have an owner, then get out of the function */
if ( MyPawnOwner == None )
{
    return false;
}

/** If we have a weapon... */
if ( W != None)
{
    /** Values for the trace */
    StartTrace = W.InstantFireStartTrace();
    EndTrace = StartTrace + W.MaxRange() * vector(PlayerOwner.Rotation);
    HitActor = MyPawnOwner.Trace(HitLocation, HitNormal, EndTrace, StartTrace, true, vect(0,0,0),, TRACEFLAG_Bullet);
    DrawDebugLine(StartTrace, EndTrace, 100,100,100,);

    /** Projection for the crosshair to convert 3d coords into 2d */
    ScreenPos = Canvas.Project(HitLocation);

    /** If we haven't hit any actors... */
    if ( Pawn(HitActor) == None )
    {
        HitActor = (HitActor == None) ? None : Pawn(HitActor.Base);
    }
}

/** If our trace hits a pawn... */
if ((Pawn(HitActor) == None))
{
    /** Draws the crosshair for no one - Grey*/
    CrosshairSize = 28 * (Canvas.ClipY / 768) * (Canvas.ClipX /1024);
    Canvas.SetDrawColor(100,100,128,255);
    Canvas.SetPos(ScreenPos.X - (CrosshairSize * 0.5f), ScreenPos.Y -(CrosshairSize * 0.5f));
    Canvas.DrawTile(class'UTHUD'.default.AltHudTexture, CrosshairSize, CrosshairSize, 600, 262, 28, 27);
    return false;
}

    /** Draws the crosshair for friendlies - Yellow */
    CrosshairSize = 28 * (Canvas.ClipY / 768) * (Canvas.ClipX /1024);
    Canvas.SetDrawColor(255,255,128,255);
    Canvas.SetPos(ScreenPos.X - (CrosshairSize * 0.5f), ScreenPos.Y -(CrosshairSize * 0.5f));
    Canvas.DrawTile(class'UTHUD'.default.AltHudTexture, CrosshairSize, CrosshairSize, 600, 262, 28, 27);
    return true;

}


texts: Animation Texture spread out when animation on 3dsMax

texts: I have a 3d model of a human biped, i did the skeleton and attached it to my 3d model with a skin modifier. But when i move his arms a part of the trunk is comming too . Is it possible to fix this ?


texts: Weapon as camera's child, rotation messed up

texts:
I put my weapon as a camera child, it works, but when i rotate my player it seems the weapon rotate a little too.

I'll attach some images so you can see it.

As you can see, when i look up i can see a little bit more of the weapon and when look down to.
I'm using the default 1st person script.
Am i missing some important point here?

Regards, Alex.


texts:
I am looking for a way to include scrolling text boxes in a jMonkey game.  I have, of course, looked around online and could not find any examples or libraries that fit.

My goal is to have "quests" pop up for the user in small graphical boxes, containing quest text.  The quest text might be longer than the quest box (which was easy enough to generate in jMonkey), so I am left with the problem of generating scrolling text boxes.

Before I set off on a long venture to properly adjust, indent, and scroll text inside boxes, I was wondering if any knew of existing examples or libraries. I have a hard time believing I'm the first person to using jMonkey that needed scrolling text or quest functionality.


texts: How do I handle specific tile/object collisions?

texts:
What do I do after the bounding box test against a tile to determine whether there is a real collision against the contents of that tile?  And if there is, how should I move the object in response to that collision?

I have a small object, and test for collisions against the tiles that each corner of it is on.

Here's my current code, which I run for each of those (up to) four tiles:

// get the bounding box of the object, in world space
objectBounds = object->bounds + object->position;
if ( (objectBounds.right >= tileBounds.left) &&
     (objectBounds.left <= tileBounds.right) &&
     (objectBounds.top >= tileBounds.bottom) &&
     (objectBounds.bottom <= tileBounds.top))
{
    // perform specific test to see if it's a left, top , bottom
    // or right collision. If so, I check to see the nature of it
    // and where I need to place the object to respond to that collision...
    // [THIS IS THE PART THAT NEEDS WORK]
    //
    if( lastkey==keydown[right] && ((objectBounds.right >= tileBounds.left) &&
                                   (objectBounds.right <= tileBounds.right) &&
                                   (objectBounds.bottom >= tileBounds.bottom) &&
                                   (objectBounds.bottom <= tileBounds.top)) )
    {
        object->position.x = tileBounds.left - objectBounds.width;
    }
    // etc.


texts:
I am working on a 2D side-scrolling action platformer.

I am currently working on the state logic for my enemies. These are humanoid enemies that walk on the ground

They currently have  idle, patrol, chase, engage, and attack states.

The default state is patrol, where they walk back and forth on a platform. If they encounter a wall or cliff, they idle for a few seconds then turn around and patrol in the other direction.

If the player comes within a chase_radius, they start chasing the player. If the player comes within an attack_radius, they enter an engaged state where they attack every few seconds.

Currently, I don't have enemies colliding with one another. I allow them to overlap each other. This is nice in the event that two enemies are patrolling in opposite directions. They simply walk passed each other.

The problem is that when two enemies are chasing a player, when one enters the engaged state, they stop and idle until they attack. The second enemy continues to walk until they too are within attack range. They then stop directly on top of the previous enemy and idle until they attack.

In this case, the enemies pretty much completely overlap and it turns an interesting situation with two enemies into a situation with essentially one enemy.

What are some techniques or design choices I can make to prevent this ugly overlap? Ideally, I'd like the enemies  to be able to walk passed each other when they are not engaged, but to do something different during combat so that they don't end up overlapping.

I have access to all the normal stuff (for example, raycasting, collision boxes, etc.).

Similar Questions:

Enemies overlapping (involves pathfinding, and isn't applicable to 2D sidescroller where enemies walk on ground.)
How to avoid enemies overlapping each other when chasing player in Unity? (solution of gradually pulling enemies apart when they overlap won't look natural with humanoid enemies that do melee attacks).


texts: How to model / where to store relational data between classes

texts:
I'm trying to figure out the best design here, and I can see multiple approaches, but none that seems "right."

There are three relevant classes here: Base, TradingPost, and Resource. Each Base has a TradingPost which can offer various Resources depending on the Base's tech level.

Where is the right place to store the minimum tech level a base must possess to offer any given resource? A database seems like overkill. Putting it in each subclass of Resource seems wrong--that's not an intrinsic property of the Resource. Do I have a mediating class, and if so, how does it work? It's important that I not be duplicating code; that I have one place where I set the required tech level for a given item. Essentially, where does this data belong?

P.S. Feel free to change the title; I struggled to come up with one that fits.


texts: How could you use mirror in unity to network across multiple networks rather than only LAN (Port Forwarding?)

texts: I've been working on a game for my friends and I to play during quarantine but I can't figure out or find any information on networking using mirror. Everything I see gives vague answers to even vaguer questions that assume you have prior knowledge of networking. Could anyone give me any sort of direction on how to port forward using mirror or if there's a better solution?


texts: Make Camera Look at point using a World transformation matrix?

texts:
Variants of this question might have been asked on this site, but none of the answers I found worked in my case.

I am trying to make a Camera look at a point. The camera has a world transformation matrix, which is used to calculate the front vector, the eye position when making the view matrix finally.  My camera is treated like any other object in the scene and thus has a world transform. I want to be able to modify this world transform, and that should automatically affect the camera.I want to actually modify the world transform of this camera so that it will "LookAt" a point.

For this, I modify the Rotation term of the world transform (R in T * S * R) like this:

WorldTransform::SetLookAt( float x, float y, float z ) {

    vec3 lookPoint = vec3 ( x, y, z );

    vec3 lookDir = normalize( lookPoint - m_position  );

    float lookLengthOnXZ = sqrtf( lookDir.z*lookDir.z + lookDir.x*lookDir.x );
    m_rotationX = degrees(atan2f( lookDir.y, lookLengthOnXZ ));
    m_rotationY = degrees(atan2f( lookDir.x, lookDir.z ));

    RotateAbs( m_rotationX, m_rotationY, m_rotationZ );

    UpdateMatLocal( );
}

Basically, I already have a function that can set the rotation (RotateAbs()), so I calculate the pitch, yaw and roll angles and pass them to there.

While calculating the view matrix, I just do:

void Camera::Update( ) {
    if (m_pTransform.m_pointer == nullptr) return;

    vec3& position = m_pTransform->GetPosition( );
    m_look         = m_pTransform->GetForward( );
    m_lookAt       = position + m_look;

    //Calculate the new matrix
    m_view = glm::lookAt( position, m_lookAt, glm::vec3( 0.0f, 1.f, 0.0f ));

}

This sort of works, the camera starts deviating from where it should be looking at after a while. What am I doing wrong?


texts: How can I deploy a JavaScript game into the iOS app store?

texts:
Unfortunately, I don't have a Mac, so I can't develop for iOS.

I understand that HTML5 apps run in the browser, but is there a way to make an HTML5 app (e.g. a JavaScript game) and get it deployed onto the app store through Apple? How should I package and submit it?


texts: How well does Unity 3d work for both Android and iPhone?

texts: First off this question might be a bit broad so I apologize if it is. I am really just looking for peoples experiences and personal knowledge on the subject. I am looking to create a game for both Android and iPhone platform. I know Unity is a great game engine and my question is how well does it work for creating one code base to build for both Android and iPhone platforms? Time is a constraint on this project so I am very interested in how smoothly the process usually is when trying to build both applications and how much custom code must be written for each specific application. Any insite that people have on this topic would be much appreciated thanks.


texts: Why does my 2d collision and movement not work properly?

texts:
I'm trying to write(in c++ using sdl) a mario like game as in a tile based world with by pixel movement for the character and I've run into some problems I cannot seem to find the source of:

1.The player won't collide with the walls.

2.when moving through open space the player sometimes stops moving and then becomes unmovable in either direction.

I'm not sure where the problem is and I would love your help finding these issues and any advice in general is appreciated. thanks!

Here is all the code:

http://pastebin.com/FGxW2x3T
//sorry I can only post two links cause I don't have 10 rep.

Here is the collision detection function and player input/movement functions. http://pastebin.com/jWaZPDBm


texts: Sprites being skipped over in simple sprite change script

texts:
Each instance of the prefab in question has a copy of this script on it, but they seem to be interfering with each other in some way.

I would forego prefabs, except the final game I'm prototyping for will use procedural generation for building placement.

The problem is: it skips to dmgSprite2 and dmgSprite3 really frequently, only maybe 1 in 4 buildings performs as it should, going down the line of sprites appropriately.

Can someone explain to me what is happening to cause this?  I tried playing with coroutines and multiple loop iterations and nothing is fixing the issue.  I've been at this all weekend with varying success, but no permanent solutions.

void OnCollisionStay2D(Collision2D collision)
{
    if (Input.GetKeyDown(KeyCode.Space)) //If space is pressed..
    {
        while(collision.gameObject.name == ("Player")) //While Player is colliding..
        {
            BlowUp(); //Initiate sprite change.
            Debug.Log("Blow Up");
            return;
        }
    }
}

void BlowUp()
{
    if (spriteRenderer.sprite == mainSprite) //If the sprite is mainSprite..
    {
            spriteRenderer.sprite = dmgSprite; //Change to dmgSprite.
            Debug.Log("Check 1");
    }

    else if (spriteRenderer.sprite == dmgSprite) //If the sprite is dmgSprite..
    {
            spriteRenderer.sprite = dmgSprite2; //Change to dmgSprite2.
            Debug.Log("Check 2");
    }

    else if (spriteRenderer.sprite == dmgSprite2) //If the sprite is dmgSprite2..
    {
            spriteRenderer.sprite = dmgSprite3; //Change to dmgSprite3.
            Debug.Log("Check 3");
    }
}


texts: How do I rotate finger joints using controller input?

texts:
Suppose I have an index finger composed of 3 cubes which all contain Rigidbody which have isKinematic set to true.
In a hierarchy they are the parent and children like this cube1 -> cube2 -> cube3

I want to control how my finger curls using the controller which outputs strength in range 0-1, e.g. the ArrowUp button.
Put simply, if I hold the up button, all the cubes would rotate around Z for 60 degrees. And if I release the button, it would rotate back to 0 degrees. (All degrees in between 0-60 are valid when the up strength is between 0-1)

How do I rotate the finger while also making it collide with other objects? For example, you could use the finger to kick a ball.

If I don't care about the collision, I can just use transform.Rotate(0, 0, buttonUpStrength) in the Update() function and attach this script to all the cubes.
But I care about collision and rigidbody.MoveRotation() is not enough because the position of each child will stay at the same absolute position when I use it. So I need to use rigidbody.MovePosition() to move the children relative to the parent also. But it's still not enough, the animation is not smooth, I want the animation to be smooth so I'm thinking that AddTorque() might be a better way out, but I don't know how to use it as isKinematic=true objects cannot be used with AddTorque().

What is a smarter, simpler way of making the finger kick a ball, without the finger being pushed back by the ball?

This is how my finger looks like, it's just a cube.

This is my script, that I attach to all cubes, in the inspector, I set cube1's angle to be 60. The children will just copy the angle of the parent:

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

public class TestJointRotation : MonoBehaviour
{
    public float angle;
    private Rigidbody rb, rbParent;
    private Vector3 originalPos;
    private Quaternion originalRot;

    void Start()
    {
        rb = GetComponent<Collider>().attachedRigidbody;
        if (transform.parent != null)
        {
            rbParent = transform.parent.GetComponent<Collider>().attachedRigidbody;
        }

        originalPos = transform.localPosition;
        originalRot = transform.localRotation;
    }

    void Update()
    {
        if (rbParent)
        {
            angle = rbParent.GetComponent<TestJointRotation>().angle;
        }

        var rotation = Quaternion.identity;
        if (rbParent)
            rotation *= rbParent.rotation;
        rotation *= originalRot;
        rotation *= Quaternion.Euler(0, 0, Input.GetAxis("Vertical") * angle);
        rb.MoveRotation(rotation);
        if (rbParent)
            rb.MovePosition(transform.parent.TransformPoint(originalPos));
    }
}


texts: Sampler object not changing texture filter

texts:
I am currently binding a sampler object to a texture (GL_TEXTURE12 to be specific) with

glBindSampler(12, sampler);

and the initial settings are very visible compared to the textures own settings. But when I change the samplers parameters with

glSamplerParameteri(sampler, GL_TEXTURE_***_FILTER, filter);

the texture filters just the same as it did before with no apparent change from any perspective.

I have tried re-binding the texture to the sampler again after the parameter change but I'm pretty sure this isn't required.

What changes can I make to get this working?


texts: I was wondering how I can get my 110+ .png map tiles conveniently into a 1:1 pixel ratio size map .png. I've been scrolling through Google and forums for the free ware game that I am modding, but the app I'm using recognizes only .png files, and I want more than 1% of the map. If you guys know of a program I would be very appreciative.


texts: What is the age histogram of people who play casual mobile games like Cut The Rope, Angry Birds and so on?


texts:
How to use functions like ScreenToRayPoint() in Camera class?

I have used this code:

Ray ray = camera.ScreenPointToRay(Input.mousePosition);

and it says

  Component.camera is obsolete, instead using GetComponent()

Then I tried these:

Camera cam = GetComponent<Camera>();

Ray ray = cam.ScreenToRayPoint(Input.mousePosition);

and it says

  Camera doesn't contain a definition of ScreenPointToRay and no extension method 'ScreenPointToRay' accepting a first argument of type 'Camera' could be found.


texts: Why would a game developer choose Direct3D instead of something with more cross-platform support?

texts:
Why would a game developer choose to use Direct3D (D3D), instead of using something with more cross-platform support, like the Vulkan or OpenGL APIs?

I know the hardware is actually rendering.


texts: Cross-platform game to be wrapped into a native iOS/Android app

texts:
I need to build an app like Lumosity (https://play.google.com/store/apps/details?id=com.lumoslabs.lumosity) that is native app and have some game screens.

So the question is: Is there a way to build a cross-platform game that I could wrap it into a native iOS/Android app?

I've read about Cocos2D-x that is great to build the hole game but I found nothing about wrapping like GLView as a subView.


texts: Dynamic vertex buffer mapping call order

texts:
From the book Introduction to 3D Game Programming with DirectX10:

 // Update the vertex buffer with the new solution. Vertex* v = 0;
 HR(mVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&v ));

 for(DWORD i = 0; i < mNumVertices; ++i) {
     v[i].pos = mCurrSolution[i];
     v[i].color = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f); }

 mVB->Unmap();

  The ID3D10Buffer::Unmap function must be called when you are done
  updating the buffer. The argument D3D10_MAP_WRITE_DISCARD passed into
  the first parameter of the Map function instructs the hardware to
  discard the buffer and return a pointer to a newly allocated buffer;
  this prevents the hardware from stalling by allowing the hardware to
  continue rendering from the discarded buffer while we write to the
  newly allocated buffer.

The bold text says that it's supposed to render while we are writing to the buffer.
Doesn't that mean that the Draw() call should happen right after we called the Map() function?

If not, why not?

EDIT:

A second question about dynamic vbuffers: When we don't only want to change the vertices inside the buffer, but we also want to create additional vertices, would it be more performance-friendly to just create a static buffer and recreate the buffer?


texts: How to create inline glow shader for 2d polygon in CG using Unity Shader Lab?

texts:
So here is what I am trying to do. Given irregular polygon (on the left) I would like to be able to create a shader that would resemble Photoshop inline glow effect with opaque fill (on the right).

Creating similar effect for 3d object I can achieve with Fresnel function. However, I am not able to do it for a flat surface of any given irregular 2d polygon.

EDIT

I am planning on using Voronoi method to generate polygons and then connecting individual polygons to territory shapes based on which player owns them. Which, then will have border material applied. What I need is effectively border (or territory) shader. That means shader has to work for more irregular shapes, like the one below.


texts: When should I use velocity versus addForce when dealing with player objects?

texts: I'm confused about these two methods in the Unity framework.  Both make the player object move, stop, change direction, etc.  When should one be used over the other and when is one appropriate?


texts: Realistic planetary terrain generation with weights

texts:
I need terrain generation for a planet. The planet will be divided up into several hundred hexes, and I need it to be realistic and based on weights. I have dabbled in terrain generation before, but nothing like this. So I figure it would be a good idea to ask the community for answers, recommended articles or the like.

By realistic, I mean not just random hexes, but continent shaped things with a few islands. More desert around the equator and more ice around the poles.

I also have two weights I need to base it around: ice percentage and water percentage. That means that around XX% of the planet will need to be water.

Does anyone have any advice or places to start? Generating arbitrary terrain is easy, but something a bit more "organic" like this seems rather difficult.

It also needs to be seamless. Should be obvious since it's a planet, but no harm in pointing it out.


texts: Does somebody know of a testcase(s) of libRocket

texts:
Today I implemented the interfaces for libRocket in my engine using OpenGL 3.3. I got a standard RML file and some fonts and images which where needed in this RML file. It seems that the page/RML I'm rendering know is the correct one, but I'm not 100% sure. Also because I still don't know a lot of RML and it is a fairly complex one.

So my question: Are there any testcases for example an RML with images and fonts with the result as it should be rendered in a PNG or some other image format? If there aren't would somebody who actually implemented the libRocket interface correctly be so kind and share a result of a rendering in a PNG with the RML to be rendered?


texts: Making a 2D Platformer in C++/SDL. Looking for tutorials/examples/resources

texts:
I have a lot of experience with C++, but I have no experience with game programming.  This summer I plan to create a 2D platformer from scratch using C++/SDL for the learning experience.  I am looking for as many resources as possible to help me get started.  Good source code, tutorials, anything.

One of the best tutorials I've found are the inactive jump 'n' run dev tutorials by the late Florian Hufsky.  Any similar tutorials?


texts: How do you market assets that are niche but that those people definitely want?

texts:
I just got done canvasing/surveying developers, and it is clear that there is a market for a few niche categories of audio assets that I suspected would be useful to them. While the overall category of assets is commonly desired, it can only be broken down into separate categories, which individually are completely niche due to the wide variety of games nowadays.

How can a niche but useful asset be effectively marketed to (mostly indie) game developers? It is known that there are people out there who want it, but the likelihood of a completely random individual wanting it is low. So if the asset was created, and there was low competition among asset producers for it, how could one ensure at least some of those people find it (without actually cold-calling them)?
I would explain in more detail, but I don't want to come off as though I'm trying to advertise anything here.


texts: After creating the Build of my Game, part of the UI isnt interactable anymore

texts:
This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem.

When I start my game normally through the Unity Editor (is this the right name?), everything works fine. Everything is interactable and the functions behind the buttons, dropdowns etc work as well. Since I can't test resolutions, fullscreen inside the Unity Editor, I decided to build my game and test it there. Everything still works fine, but the Options A Dropdown (this shows the resolutions), the Fullscreen Button and Graphics Dropdown arent interactable anymore.

After some testing myself, I found out, that the functions still work. If I click on the volume slider and go up through the WASD Keys, then I can still use the UI Elements and functions behind them still work.

What I tried:

I got the help to put my Event System to "Always enabled", which didnt helped.

Side Information:

The dropdowns are from Textmesh Pro, dont know if this is important or not.


texts: Matrix stack from direction vector chain

texts:
I've implemented an IK system for a grabber arm based on several straight segments, starting from a fixed point. The IK is based on a mass-spring simulation, which eventually rests. What I'm left with is an array of positions in world space, one for each joint position, and an extra one at the end.

I need to convert these world positions into one quaternion rotation for each joint, so that I can build a hierarchy of transformation matrices (I'm using quaternion for the rotation part). each segment of the arm is an instance of a segment model that I want to translate into world space. The hierarchy works by inheriting previous rotations and translations. The issue I'm facing is describing each progressive joint rotation relative to the previous rotations (rather than relative to the world).

So far my approach is:

Initially the grabber arm point upwards, so the root rotation is described as the orientation difference from the vector (0, 1, 0) - (I'm using GL coordinates).

Keep the direction vector of the previous joint, prevDir, initially (0, 1, 0).
Keep a quaternion of the accumulated rotations, rotChain, initially the identity quaternion.
From root to tip, for each joint:

Take the next joint position and subtract the current position and normalize, to get a direction vector dir. This is why there's an extra point in the array, for the last joint
Compute the cross product between prevDir and dir, which should give a world rotation axis side, between the previous and current joint. Also compute the dot product, dot.
Rotate the side vector by rotChain, to bring it into the current joint's orientation.
Create a quaternion rot on the axis side and rotation acos(dot). This should represent the rotation of the current joint relative to the previous one.
Post-multiply rot onto rotChain, to add the effect of the current rotation.
Update prevDir to dir.

This only works as long as all the segments are on the YZ plane, which I think is a fluke. What am I doing wrong?

I'm only using quaternions as I'm trying to invert rotations easily.
As per this answer, I get the sense I could instead directly derive an orientation matrix from dir and side. Would this work better?


texts: Space to Switch to Hand Tool in Tile Palette?

texts:
Hi I just download a Utility called: Hold Spacebar for Hand (drag) Tool
I read the code and I can understand it, but now I wondering how can I modify this to support the same functionality but works in Tile Palette tab, thanks!


texts: texconv produces texture with same size using BC1 or BC4

texts:
According to msdn, the BC1 block compression format is for images with 3 color channels and 1 bit alpha channel and the BC4 is for images with 1 color channel and no alpha.

Using the same RGBA input image I would expect the output of this command

texconv.exe -f BC1_UNORM diffuse.tga

to be larger than the output of this other command

texconv.exe -f BC4_UNORM diffuse.tga

Since the resulting DDS should only have information on one channel, but both DDS have the exact same size. The only difference being that the BC4 compressed one appears red (as expected).

Is this the expected output?


texts: Where can I pay artists to make models for my game?

texts:
Lets say I get some money for my hobby project, and I would like to start filling it up with good models, instead of some cheap placeholder ones. What are some sites where I can pay people to make models for the game? How much would it cost per asset?

Edit: I don't want to hire anybody. I just want to pay them for individual assets.


texts: How to get position of next object that closest to player,when player is move forward to nearest every time?

texts:
I have a scene that looks like the following picture:

The Player has a RigidBody2D and all the steps have a BoxCollider2D. All steps are tagged with a 'step' tag.

I would like to let the player move to the next step, every time the user presses a key. In this case, I'll need to get the position of the next step that is the closest to the player, every time the player moves to the next position.

I have tried the following so far:

using UnityEngine;
using System.Linq;

public class Box : MonoBehaviour
{
    //the rigidbody of the box
    private Rigidbody2D player2D;

    // Start is called before the first frame update
    void Start()
    {
        player2D = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Vector2 targetPosition = GetNextTargetTransform(player2D.position );

            //here set trajectory to move from current position to target position
            Vector2 trajectory = SetTrajectory(player2D, targetPosition);
            player2D.AddForce(trajectory, ForceMode2D.Impulse);

            //after reach the position update player position to current position
            //player2D.position = targetPosition;
        }
    }

    public Vector2 GetNextTargetTransform(Vector2 player2Dposition)
    {
        GameObject[] step = GameObject.FindGameObjectsWithTag("step");

        //here is the code to get the nearest object using LinQ
        var nearest = step.OrderBy(t => Vector2.Distance(player2Dposition, t.transform.position)).FirstOrDefault();

        Transform nearestPosition = nearest.transform;
        Vector2 targetPosition = new Vector2(nearestPosition.position.x, nearestPosition.position.y);

        return targetPosition;
    }
}

I am able to get the position of the first step when a button is pressed, but when I press the key again, I am unable to get the position of the next step (and thus remain on the first position).

I've added player2D.position = targetPosition; after AddForce(...) and the player will directly appear on the first step and move to the next one, which is not the result I want.

Question

How do I get the position of the nearest step, every time the player moves to a new step?


texts:
Using:

Unity 4.6.1 Pro

Visual Studio 2013 Pro, c#

Team Foundation Connected to git vc

Windows 7 Premium

Building 2D iOS app (2D set up)

Details:

Periodically, this error is occurring. There is no pattern to invoke this error so far.

I then found this on the official Unity forums: Strange error showing up

But, I would like to avoid creating an entirely new project and re-importing everything, since it is getting to become a slightly large project. I do remember deleting an asset out of the file directory(not in unity), on accident, so this may be the issue. Is there any way to clean/wipe/fix this issue, w/o doing a fresh project and import?

I appreciate the guidance.


texts:
I'm using Unity3D version 5.0.

I'm wondering what the best way to deal with changing resolutions in Unity is.  In Swift I can just use the @x2/@x3 in order for it to pick the correct sprite for it to use.  Is there a similar mechanism in Unity?

Thanks


texts: How to model chess knight movement in GameMaker?

texts: I am making a chess game in GameMaker, and I have the basic movement down for all of the other pieces except for the knight. I am using a system where I have an if statement that checks if the mouse is in a location that it can move too, then if it moves the piece there. For example, the rook code is (mouse_y div 64) *64 == y || (mouse_x div 64) * 64 == x. What would be an expression that would work for knights? Would this strategy even work for knights?


texts:
Does radiosity work with skylight (directional light)? From reading online it sounds like it was intended to work with point lights but I would really like to make it work with skylight if possible.

If I did misunderstand how would I make this work with skylight?

The form factor attenuates for distance, area, and orientation of the patches. It doesn't seem like that would all apply in skylight.

I have a primitive implementation of radiosity in the cpu using ray casting.

Any help is greatly appreciated.


texts: How does GL_INT_2_10_10_10_REV work for color data?

texts:
Can anybody tell me how exactly to use GL_INT_2_10_10_10_REV as type parameter in glVertexAttribPointer()?

I am trying to pass color values using this type. What is the significance of "REV" suffix in this type? Does it require any special treatment in the shaders?