texts: I've been keeping a blog for my current Android game and as I get closer to an actual playable version of the game, screenshots just aren’t enough to show new progress anymore. What I need is video. The problem is, my game won’t run on the current emulator (uses OpenGL ES 2.0), and my computer couldn’t run the emulator if it wanted to anyways. So desktop video capture is out of the question. The only real idea I have is holding the phone in front of the only video camera I own: a webcam… yeah. Does anyone know a better (preferably free) way to capture video from an Android device?


texts: How to simply print (write) text on a Surface in SDL.NET?

texts:
as i told in previous question, i'm using SDL.NET (wrapper in C# of SDL). Unfortunately the API website is down so i'm trying to learn it by myself.
I would like simply to print text on my screen / surface ... i don't know how to do!

My goal is to print variable status/values, to "debug" directly on the run and on the screen (in the lower corner for example).
Can somebody help me ?

Thank you


texts: How to force play area corners to Lighthouses in Unity

texts:
I'm working for a guy that wants to recreate real environments in VR and superpose them for business demos. Think of one of those mall kiosks where you "enter virtual reality" and at first it looks exactly the same as regular reality until you start interacting with objects and the virtual elements start being superposed. Basically, AR in VR.

To do this, I have an exact model of the kiosk, but I need to be able to force the play area in vive and unity to be always the same and equal to the dimensions of the real space, so that my model can superpose the actual world objects. Is there a way to force the play area to be the same as the distance between the lighthouses?

Additionally, is there a way to force the lighthouses to never recalibrate after the initial setup(as it does when someone moves in front of them for example)?


texts: What information should be stored in a database for a MOBA game?

texts: I'm wondering what information should be stored in a database when developing a MOBA like game? For example: the current item a unit has, how much gold a player has, etc...


texts: How to use PhotonPeer in Unreal Engine 4.8

texts:
I'm trying to implement PhotonPeer in Unreal Engine 4.8 but I'm stuck at the connect function. I need to provide an AppId, but nothing I try is accepted by UE4.

Here's my code:

DALGameInstance.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "Engine/GameInstance.h"
#ifdef __clang__
#pragma clang diagnostic ignored "-Woverloaded-virtual"
#endif
#if _EG_WINDOWS_PLATFORM
#include "AllowWindowsPlatformTypes.h"
#endif
#pragma warning (disable: 4263)
#pragma warning (disable: 4264)
#include "Photon/Photon-cpp/inc/PhotonPeer.h"
#include "Photon/Photon-cpp/inc/PhotonListener.h"
#pragma warning (default: 4263)
#pragma warning (default: 4264)
#if _EG_WINDOWS_PLATFORM
#include "HideWindowsPlatformTypes.h"
#endif
#include "DALGameInstance.generated.h"

/**
 *
 */
UCLASS()
class DALGAME_API UDALGameInstance : public UGameInstance
{
    GENERATED_UCLASS_BODY()

public:
    //UDALGameInstance(const class FObjectInitializer& ObjectInitializer);
    ExitGames::Photon::PhotonPeer* peer;
    ExitGames::Photon::PhotonListener* listener;
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DALGameInstancePhoton)
    FString ServerAddress = "127.0.0.1:5055";
    UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = DALGameInstancePhoton)
    FString ApplicationName = "MasterServer";
};

DALGameInstance.cpp

// Fill out your copyright notice in the Description page of Project Settings.

#include "DALGame.h"
#include "DALGameInstance.h"

UDALGameInstance::UDALGameInstance(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
    peer = new ExitGames::Photon::PhotonPeer(*listener, ExitGames::Photon::ConnectionProtocol::UDP);
    UE_LOG(LogTemp, Warning, TEXT("Connecting to server"));
    if(!peer->connect(*ServerAddress, **ApplicationName**))
    {
        UE_LOG(LogTemp, Warning, TEXT("Connection failed"));
    }
    else
    {
        UE_LOG(LogTemp, Warning, TEXT("Connection established"));
    }
}

The part with ApplicationName is the problem. BuildTool complains No suitable conversion from FString to const nByte. I have tried everything to get this up and running but with no luck at all.

Does someone have the same issue or a hint at what I missed?


texts: So I got some code and I'm using pytmx to load the maps, but the animated tiles don't seem to animate in my pygame game. Is there a setting to change that or do I need to write the animation code myself?


texts: Creating Font Textures in Direct3d without D3DX

texts:
Update: The completed solution using Nathan Reed's answer is posted in my answer below

A few open source programs I've seen that render installed fonts do something like this...

Create a texture for the font
Draw font to texture using native calls
Store the coordinates for each character
Create a vertex buffer with a quad for each character
Render the vertex buffer using the font texture

But I'm really having trouble getting this to work consistently. GetTextExtentPoint32A() for Win32 font sizes which does NOT include italic support and seems to cut off some of the stranger fonts.

Here is an example output from my code. Notice the cut off edge of the Q and a few other characters. A much more exaggerated version happens when rendering italics.

http://i30.photobucket.com/albums/c308/thentsc/font_test.jpg

The code looks something like this...

for (uint8 c = 0; c < 127 - 32; c++)
{
    str[0] = c + 32;
    SIZE size;
    GetTextExtentPoint32A(hDC, str, 1, &size);
    if (x+size.cx+1 > m_TextureSize)
    {
        x  = 0;
        // 1 pixel vertical margin
        y += size.cy + 1;
    }

    uint32 Diff;
    ExtTextOutA(hDC, x+0, y+0, ETO_OPAQUE | ETO_CLIPPED, NULL, str, 1, NULL);
    m_fTexCoords[c].Left = x/m_TextureSize;
    m_fTexCoords[c].Top = y/m_TextureSize;
    m_fTexCoords[c].Right = x+size.cx/m_TextureSize;
    m_fTexCoords[c].Bottom = y+size.cy/m_TextureSize;

    // 1 pixel horizontal margin
    x += size.cx;
}

The image above is actually just a render of the whole texture stretched from -1,-1,0 to 1,1,0 not using the stored texture coordinates to show clipping due to GetTextExtentPoint32A.

Again this works fine for some fonts but looks terrible for others and doesn't support italics.

It is designed to work in a system like this...

cFont* g_Font;
cTextObject g_TextObject;

Setup()
{
    g_Font = SetupFont("Arial", BOLD | ITALIC, 24pt);
    g_TextObject = CreateTextObject("The quick brown fox...", g_Font, X, Y);
}

OnRender()
{
     g_TextObject->Render();
}

So in general I guess my question is what is the correct approach for this issue?

Should I just let each text object have a texture and on text object creation use the GDI to render all text to it (which would bypass the italics and font face problem)?

But then wouldn't texture memory usage get out of hand?


texts: Are there alternatives to ChatBlade similar in features?

texts:
ChatBlade is an MMO middleware for handling client side chat in (massively) multiplayer environments. I am looking for a royalty-free, cheaper (<1k) alternative (C++ or dll preferred) that would do the same before deciding on having to spend time developing an own solution.

Any help is greatly appreciated.


texts: Handling raycast reticle aiming/tracking if no geometry or colliders present?

texts:
My third person aiming system is really coming together, with a Canvas reticle that is driving the direction of a Raycast which is then aligning the weapon barrels. The problem I'm running into now is that the barrels lose tracking when aiming at the sky or anywhere there is not geometry or colliders.
I've considered:

Hidden geometry/colliders everywhere in the sky but seems inefficient.
Non-handle, reticle goes red/gun deactivates which is interesting but not what I'm going for.
If Raycast hit is null, switch to another form of tracking which I have found any that are accurate enough.
Dynamic reticle opens real wide and gun gets wild - turn it into a game mechanic.

None of these actually solve the problem though. Is there a code based approach to handling this to maintain tracking when there is no Raycast hit?  Any thoughts would be appreciated!


texts: Where can I find a opengl pixel shader example for smooth SpotLight?

texts:
I am using Ardor3D, and find the spotlight is quite bumpy. Anybody has a good pixel shader can smooth the edges of the spot light?

thanks,


texts: Problems when randomizing x and y position of a picturebox

texts:
So, I'm making a simple game. It's like snake but the picturebox doesn't grow. In the game, you have to get fruits and other objects.
Look at berry's code:

public class Berry : PictureBox
{
    public bool ON_SCREEN;
    public Berry()
    {
        this.BackColor = Color.White;
        this.Size = new Size(20, 20);
    }
}

And then I randomize it on a form. Like this:

public void Generator_Berry()
    {
        Berry b = new Berry();
        Random randomY = new Random();
        int rY = randomY.Next(10, 270);
        Random randomX = new Random();
        int rX = randomX.Next(10, 270);
        this.Controls.Add(b);
        b.BringToFront();
        b.Location = new Point(rX, rY);
        b.ON_SCREEN = true;
    }

So the problem is that Berry's X position is the same as Y or vice-versa. I've never got a problem like this.(It look very simple, but I can't get the solution) What is wrong?!
Am I that very stupid?!


texts: Server reconciliation for multiplayer games

texts:
Reading the usual resources on multiplayer games (1, 2, 3); I have started working on my own multiplayer game.

I used a naïve approach that for every input I receive from a client, I immediately run it on the server.

For simple units (soldiers) everything works well, however I have an issue with "always moving" units (such as jet fighters); They require queuing inputs on the server (small delay, less than 100ms) and performing them in delay - and I read elsewhere (1, 2) that you should allow a window to receive inputs longer than said delay, since latency is variable (and could easily reach over 100ms) and reconcile the player's input.

Now I understand how this works for simple input such as movement, but what about using weapons / more advanced input?

What happens if player input comes with a delay, where he wishes to fire his weapon - what do I do? When do I notify other players of the shot? What about it's result? What if my cool-downs are out of sync due to this reconciliation?

Thanks.


texts: How do I enable a Box Collider when a timer reaches 0?

texts:
I'm pretty new to Unity, and I am trying to enable a BoxCollider from another object when the timer reaches 0, using this code:

using UnityEngine;

public class Testv2 : MonoBehaviour
{
    public GameObject otherGameObject;

    private BoxCollider Target;
    public float timeLeft = 30.0f;

    void Awake()
    {
        Target = otherGameObject.GetComponent<BoxCollider>();
    }

    void OnMouseDown()
    {
      timeLeft -= Time.deltaTime;
    }

    void Update()
    {
        if (timeLeft < 0)
        {
            Target.enabled = true;
        }
    }
}

My issue is that the timer won't go down unless I keep clicking on the object. How do I enable the timer to start when someone clicks an object, and start counting down?


texts: Quadtree having ownership of entities, worth it?

texts:
Typically, you would have a list of entities stored somewhere, and you'd use quadtree when you need some collision testing between entities for example, by inserting all of the entities and generating a quadtree, and getting the nearest ones that you need for the tests.

But I was wondering, beyond collision testing, the quadtree could be even more helpful if you didn't have a list, but the entities were directly owned by the cells of the quadtree.

For example, when you need to erase an entity, or find a particular entity, you would have to iterate through your entire list. If the quadtree owned the entities, I could pass the position of my entity and it would only seek through entities that are in the same cell.

Instead of iterating through thousands of entities, it would test 'position contains rectangle' a dozens of time, and iterate through the few entities inside the quadtree cell.

Would this even optimize time, and would it be worth it ?


texts: How to get the tangent and normal of a collision?

texts:
In my game, one of my objects casts a ray into a 2d space. If that ray were to hit another object, I'd like to draw a line that is perpendicular to the tangent of the ray's hit point. So when the ray hits the other object, a tangent is formed at the point of contact, and then I'd like to use the linerenderer component to draw a line that is perpendicular to that tangent. I already know how to use the linerenderer to draw lines, but I don't know how to get the tangent and normal from a collision.

  if (Input.GetMouseButton(0))
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        var direction = (mousePos - (Vector2)cueBall.position).normalized;

        var hit = Physics2D.Raycast(cueBall.position, direction, Mathf.Infinity, 1 << LayerMask.NameToLayer("Ball"));

        if (hit)
        {
            _line1.SetPositions(cueBall.position, hit.point); //This is the line from the cueball to the red ball.
            _line2.SetPositions(hit.point, hit.normal); //This is supposed to be the predicted trajectory of the red ball.
        }
    }


texts: Can anyone explain step-by-step how the as3isolib depth-sorts isometric objects?

texts:
The library manages to depth-sort correctly, even when using items of non-1x1 sizes. I took a look through the code but it's a big project to go through line by line!

There are some questions about the process such as:

How are the x, y, z values of each object defined? Are they the center points of the objects or something else?
I noticed that the IBounds defines the bounds of the object. If you were to visualise a cuboid of 40, 40, 90 in size, where would each of the IBounds metrics be?

I would like to know how as3isolib achieves this although I would also be happy with a generalised pseudo-code version.

At present I have a system that works 90% of the time but in cases of objects that are along the same horizontal line, the depth is calculated as the same value.

The depth calculation currently works like this:

x = object horizontal center point
y = object vertical center point

originX and Y = the origin point relative to the object so if you want the origin to be the center, the value would be originX = 0.5, originY = 0.5. If you wanted the origin to be vertical center, horizontal far right of the object it would be originX = 1.0, originY = 0.5. The origin adjusts the position that the object is transformed from.

AABB_width = The bounding box width.
AABB_height = The bounding box height.

depth = x + (AABB_width * originX) + y + (AABB_height * originY) - z;

This generates the same depth for all objects along the same horizontal x.


texts: How to make a 90 degree rotation happen over time

texts:
I'm trying to take a RotateAround function and make it happen over time. I've been tinkering with Quaternions to try and get it to work but I can't quite figure it out.

This is the code:

public class RotateCamera : MonoBehaviour {

public Vector3 rotatePoint = new Vector3(0,0,5);

public void RotateLeft ()
{
    transform.RotateAround (rotatePoint, Vector3.up, 90);
}

public void RotateRight ()
{
    transform.RotateAround (rotatePoint, Vector3.up, -90);
}

I'm applying each void to a button, and this works like a Final Fantasy Tactics camera - rotate an isometric camera 90 degrees. But it happens instantly, and I want to make it happen over time, like a second or a half a second. I'm super new to programming and I can't find any guides on this or any other posts using google, so I'm asking on here as a last resort. Thanks for any help.


texts: Manage a large number of independent actors in real-time

texts: I am working on a large scale real-time strategy game - ideally with thousands of units active at once - but I am having trouble managing all of the units at once without it becoming astonishingly slow. The problem is that it takes a while to update the positions and states of everything each time step. Do you know any design patterns/methodologies/tips for mitigating this?


texts: Can I rely on a Navmesh for X/Z movement and manually place my agent on the Y axis?

texts:
I'm generating my terrain mesh around the player (along with collision mesh and Navmesh). It's tile based, when the player moved enough I generate necessary tiles render meshes, then collision meshes and then I generate a whole new navmesh surface data (in the background) to swap with the current one. The setup is a sand desert with no obstacles and no slope too steep to climb, basically you can go everywhere.

Computing render and collision mesh is rather fast, but navmesh takes about 30s. I could not tweak values to make it faster without noticeable quality loss. I'm trying to find a workaround before going too deep this way (I might add simple obstacle later).
I tried using one navmesh surface per tile (instead of a single global one) but then I have to link them and that seem complicated and very noticeable.

I'm wondering if I could juste generate a navmesh according to an hidden plane underneath my terrain, and then simply reposition the agents along the world Y axis each frame ? Are there obvious issues that will arise or should that be fine ?


texts:
I want to create an Inputfield from Scratch in Java and LibGDX, my Question is:
How can I display only certain Parts of a String in a specific width?

For example:
My Input field GUI is 200 pixels wide. But I can write like 500 Letters maximum in my Input field. When I display this 500 letters all at once. It would be bigger than the GUI. So I want when I wrote down the first 100 letters and then write the next one that the first one disappears and the displayed text starts from the 2 Letter and then goes to the 101. And so on. Much like the Minecraft Chat Input field.


texts:
In a few games in the Android Market/Google Play Store, huge bitmaps are drawn onto the screen.

For example, the game Unicorn Dash:

and Robot Unicorn Attack:

I'm assuming the entire island (which is multiple screens long) is loaded into memory. With probably around 10 different islands, how can something like this be possible? I've attempted to do something similar in one of my games, but I always ran out of memory. The bitmaps are (estimated) at around ~2000px x 500px at the largest which comes out to about 4mb each uncompressed? If you had 10 of them it would require 40mb of memory! So obviously I'm missing something.
Is it plausible to be loading and unloading bitmaps into memory while the game runs? Or is there some other technique that I'm not aware of?

EDIT:

I extracted the images from Robot Unicorn Attack and saw that they were indeed whole images (not split up) of around 2000*500 pixels.


texts: Unity Mesh collider not working with capsule collider

texts:
I have in my Unity3d Project a capsule that represents a character and has a Rigidbody and capsule collider as components, and in my project I also have a mesh that is my terrain imported as fbx from blender.
I put a mesh collider to the terrain but the capsule goes trough the terrain as it had no colliders. Curiously, if I put a cube with a mesh or box collider, the cube does collide properly. Changing the Is Convex box in the mesh collider doesn't change anything
Any ideas?

EDIT
This is how the editor window for both, the capsule and terrain looks like:
Terrain

Capsule


texts: How can I create an outline shader for a plane?

texts:
All these toon shaders I have been seeing render an duplicated mesh behind it and extrude the normals of the vectors to make it look like it has a border, but it feels a bit hacky to me.

Basically I am trying to create an outline shader for a plane so these toon shaders do not really work.

It's probably due to my lack of deep knowledge about shaders in particular but I am really confused and would like someone to explain. I'm also a bit worried that rendering an object twice would hit the performance.

Edit: Added picture for reference. (Thanks for the edit Alexandre!)


texts: How can I make a car follow the terrain in a 2D (side-view) game?

texts:
I'd like to create a game where a car drives over a 2D terrain.
Which algorithm to use so the car will follow the mountain incline?


texts: I currently have an array of tiles which makes up the tilemap (stored as an int array) and I want an NPC to be able to move itself to the nearest tile of type X (ie find the nearest tree and chop it down). What's the best algorithm to use to find the nearest tile of a certain type given a location (x,y)?


texts: Stop animation from playing while waiting to destroy object

texts:
I'm working on functionality in Unity where if a game object's health is zero, it does and the object is destroyed.  This works fine as is, I reduce the health to zero, the die animation plays and the game object is destroyed.  I want to have the script wait a certain amount of time and then run the destroy method.  I thought using WaitForSeconds() would do the trick, and technically, it does, but the death animation continues to play until the object is destroyed.  My question is, how do I get the animation to stop playing as the script waits to destroy the object?

C#

void Die(){
    GetComponent<Animation>().CrossFade(die.name);
    //If the current animation time is greater than 90% of the entire animation length, destroy the object.
    if(GetComponent<Animation>()[die.name].time > GetComponent<Animation>()[die.name].length * 0.9){
        StartCoroutine(RemoveBody());
    }
}

IEnumerator RemoveBody(){
    yield return new WaitForSeconds(5);
    Destroy(gameObject);
}


texts: How do I make a resolution independent system?

texts:
I'm blanking on this one. I can anchor stuff on edges of course, that would make my UI resolution independent...until it changes so much that the graphics are too small. How do I scale appropriately whenever needed? How do I keep my graphics at the right proportion while scaling? I don't want them stretched if the resolution has a different proportion like 16:10 as opposed to whatever else.

Is there a true and tested approach to this? Video players show black borders because of this problem, is this not properly solvable?


texts: Unity WebGL Build: Why it shows only Empty Folder?

texts:
i'm trying to built my game, made in Unity 2018.3, and i'm trying to built it in WebGL, but the problem is this: built was succeeded, but the Folder is still Empty, and here is the problem occured:

This was never happened to me before. anybody know how to fix it?


texts: How do I expose a variable from a class in Unreal Engine 4 to blueprints?

texts:
I would like to expose to blueprints the variable CurrentTouchInterface in the class APlayerController, just like the method APlayerController::ActivateTouchInterface.

So, I'm guessing I have to change the header file PlayerController.h from this

/** The currently set touch interface */
UPROPERTY()
class UTouchInterface* CurrentTouchInterface;

To something like this

/** The currently set touch interface */
UPROPERTY(BlueprintReadOnly, Category="Game|Player")
class UTouchInterface* CurrentTouchInterface;

The point is, what do I need to do for the engine's editor to start showing the exposed variable CurrentTouchInterface in blueprints?

I'm working with UE 4.9 downloaded from the Epic Games Launcher application.


texts: Exporting a simple mesh from Blender for reading in Assimp

texts:
I'm trying to create some simple assets for using in my rendering engine. What I'm trying to do is to generate simple low poly models and then importing them into my application using Assimp. I can successfully import models I find on the web so everything works fine application-wise. But since I'm a total noob at Blender (I managed to learn some interface basics through tutorials) I just seem able to export a model with geometry information (vertex positions) and that's it. My models don't have normals or uv-cordinates, and no textures whatsoever.
What I'm asking is a simple workflow to create and export a very simple mesh to a obj or collada format that I can read into my code.


texts:
I'm trying to understand Quaternions in relation to rotation and orientation.
As an example in learning, I'm trying to rotate a point (e.g. at [0.7071, 0, -0.7071], on the unit sphere) about the line x=z (or the vector [0.7071, 0, 0.7071] for a unit vector pointing in x/z direction. It should rotate around the unit sphere, passing through [0,1,0]
I've read that "multiple rotations are just multiplication", but if that's the case, why are the following are not equivalent?
# This version does what I want, rotates a point about the line x=z
val q = Quaternion().setAngleAxis(toRadians(45), 0.7071, 0, 0.7071)

# neither of the following multiplications produce the equivalent to the above q
val qx = Quaternion().setAngleAxis(toRadians(45), 1, 0, 0)
val qy = Quaternion().setAngleAxis(toRadians(45), 0, 1, 0)
val q1 = qx.mul(qy)
val q2 = qy.mul(qx)

(My reasoning is like looking at a unit vector starting in the x direction, which if I rotate 45 degrees in the y axis would give me a vector pointing in the z=x direction, but this is clearly naive as it doesn't work)
An example plot of qx * qy (but using 5 degree rotations instead of 45) is:

The q rotation I want gives me:

My understanding is qx and qy represent rotations about the given axis, or indeed also represent orientations, and if I use these independently and plot them, I get what I would expect, a point being rotated as required.
But if I start from either one of these, why doesn't the multiplication of the other (which represents an initial orientation multiplied by a rotation) result in a rotation that would rotate a point by both the x and the y axis?
Which leads me to the question, what does qx * qy (or vica verca) represent here? (I think this is the key bit I'm not understanding.)
Is it possible to apply something to qx or qy to get the original q directly?


texts:
My animation is supposed to be used in my physics project I am making. I am using 10 millisecond setInterval() and setTimeout() and it glitches in and out.
The setTimeout() handles the clear() function in my code, but I have the setTimeout() at 9 milliseconds and it works the best. If someone can help me, here's the code:

var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var x = 10
var y = 0
var xPos = 0
var yPos = 0

function updateVariables() {
    x = x * 0.9
    y = y * -0.9
    y = y + 1
    xPos += x
    yPos += y
}

function clear() {
    ctx.clearRect(0,0,600,600)
}

function Draw() {
    ctx.fillRect(xPos,yPos,20,10)
    ctx.fillRect(0,131,600,20)
    setTimeout(clear, 9)
}

function collisionCheck() {
    if (yPos > 120) {
        yPos = 120
    }
}

function keyCheck() {
}

setInterval(Draw, 10)
setInterval(updateVariables, 1)
setInterval(collisionCheck, 10)
<canvas id="canvas"></canvas>


texts:
I setup my OpenGL viewport via

    ViewPort( 0,0,WindowW, WindowH )
    MatrixMode( Projection )
    LoadIdentity()
    MaxY = ClipNear * Tan(FieldOfView * 0.00872664626)
    MaxX = MaxY * Ratio
    Frustrum(-MaxX ,MaxX ,-MaxY ,MaxY ,ClipNear ,ClipFar)
    MatrixMode(ModelView)

Then I add rotation and move the Camera accordingly

    LoadIdentity()
    Rotated(ry,1,0,0)
    Rotated(rx,0,1,0)
    Translated(z,y,x)

However the center of the frustrum is not the middle of the Window.
It is slightly right and up in the window.

I'm sure there is a bug in my code but I can't seem to find it.
I have checked every place I could think of.

The bug could be caused by setting a wrong viewport however that doesn't seem to be the case as a similar Project (however not using modular code) works fine with the same viewport settings.

The bug could also be caused by setting a wrong Frustrum. However that also works in the other project.

Aside from that I do not know of anything that could cause this.

As my Code is written in a rather weird language posting it here wouldn't do any good.

So my question is what kind of mistake/bug can cause a behaviour like that.


texts: Spot lights - making narrow/broad spot lights give more/less intense light

texts:
When I use "normal" spot lights as presented in tutorials such as  this (with the exception that I use inverse square fall-off and then gamma correction), the spot light doesn't behave like a real spot light would, because in real life I would expect a narrow spot light to cast a brighter light than a broad one. In my primitive understanding this is because the light that would be cast outside of the spot lights casting angle is reflected on the inside of the spotlight device (e.g. flashlight) and effectively cast inside spotlights cone.

The spotlights usually presented in tutorials do not account for this, because the light calculation is still based on a spot light that distributes all of its energy evenly in a 360 degree radius, and the light that isn't visible is simply "clipped away", thus removing energy from the system.

My question is this:

I plan on accounting for this by just multiplying the outgoing color by a factor that depends on the casting angle of the spot light. The function of this factor is just

f(x) = 360/x;

This means that the color will be multiplied by 4 when the spot light casts its light in a 90 degree angle.
This function makes the assumption that the energy received by the lit area of a 180 degree spot light is twice as much as the energy received by the lit area of a 360 degree spot light.

Is this assumption correct? If not, how does the energy distribution change with the width of the spot light? Are there maybe other ways to account for this more effectively?


texts: Unity3d physics stability with low fixed timestep

texts:
I'm developing a vehicle simulator game for mobile platforms. This vehicle has some hydraulic arms. I use hinge joints and configurable joints. There can be collisions to walls etc.

When I set a low Fixed Timestep (more fixed updates, less performance) like 0.001 it runs smoothly on editor and it handles the collisions well. But on the target mobile device, the performance drops to 2-3 FPS! So 0.001 (1000 fixed updates per second) is not an option.

When I change the Fixed Timestep to its default 0.02 value or 0.01, performance becomes acceptable on mobile. But when collisions occur, the vehicle is torn apart and everything flies away at a high velocity as if there was an explosion.

How can I achieve stable physics with 0.02 Fixed Timestep?

Note: I don't set the velocity or transform position. I move the vehicle by applying torque to the wheels.

Update 1 : The problem happens when the vehicle hits an obstacle that has a collider but doesn't have a rigidbody.


texts: UV unwrapping and texturing for a voxel terrain

texts:
As sugested by another kind user, I started using MagicaVoxel to create the scenery for my game (which is in the 2.5D style of Pokémon Gen 5 or Octopath Traveler).

I managed to import the test object that I made into Blender (actually it was a .ply export so i could have all the blocks be individually shown).

Now my question is, how can I unwrap and texture 1 of the blocks and replicate this to all of them? (Is this even feasible?)

I want to apply textures similar to the blocks in Minecraft for example.


texts: How to Use Images Instead Of Drawing Primitives

texts:
I want to build backgammon game. I have successfully built the board using primitives  such as lines, triangles and circles. I'm curious whether it's possible to draw the board using images which will make the board look much nicer. Is it possible to have images of triangle and then to put on top of it tiles? How is this achieved?

For example, let's say I have 100x80 image of a triangle and a 100x20 tile image of tile. What theoretically needs to be done in order for the tile image to be shown on top of the triangle image? (each have different colors, and the width of both is the same).

P.S
I'm currently programming this in Objective C for the iOS, but I don't think it's important, as this is more of a general question.

Thanks.


texts:
I want to use a string to reference a gameobject that I already have in my code, but the console says that you can't convert a string to unityengine.object. I have a string that says aaaa and a gameobject that has the name aaaa.
using System.Collections.Generic;
using UnityEngine;

public class WorldRenderer : MonoBehaviour
{

    public Transform Tile;

    string seed = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacaaabaaaaaaaa";

    public int worldHeight;
    public int worldWidth;

    private int seedSub = 0;

    public GameObject aaaa;
    public GameObject aaab;
    public GameObject aaac;

    void Start()
    {

        transform.position = new Vector3(worldWidth / 2 * -0.64f + 0.32f, worldHeight / 2 * 0.64f + 0.32f);

        for (int height = 0; height < worldHeight; height++)
        {

            transform.position = new Vector3(worldWidth / 2 * -0.64f - 0.32f, transform.position.y);
            transform.position = transform.position - new Vector3(0, 0.64f);

            for (int width = 0; width < worldWidth; width++)
            {

                seedSub = seedSub + 1;

                transform.position = transform.position + new Vector3(0.64f, 0);
                //Here's the problem VVV
                GameObject tilepos = Instantiate(seed.Substring(seedSub * 4 - 3, 4)) as GameObject;
                //Here's the problem ^^^
                tilepos.transform.position = new Vector2(transform.position.x, transform.position.y);

            }

        }

    }

}```


texts:
Currently I am working on a 2D game just like duet game, it is my first game
(Unity 2D).

When I press left key both points rotate fine. But when I press right, the points are not rotated.

So my problem is why do both points rotated only in one direction

Code:

public class TouchControll : MonoBehaviour
{
  float movespeed = 3;
  float angle = 45;

  void Update()
  {
    if (Input.GetKey(KeyCode.LeftArrow))   // when i m press leftarrow both point should be rotate fine
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Horizontal") * angle * movespeed);
        Debug.Log("moveleft");
    }

    if (Input.GetKey(KeyCode.RightArrow))  // problem is here when i m press right arrow key both point are not rotated
    {
        transform.Rotate(Vector3.forward * Time.deltaTime * Input.GetAxis("Vertical") * angle * movespeed);
        Debug.Log("moveright");
    }
  }
}

Output:

create a empty gameobject:

first circle

second circle


texts: Has anyone got the Krypton Lighting Engine working in MonoGame for Windows 8?

texts:
I've converted the core of the Krypton Lighting Engine so that it's compatible with Windows 8.

The trouble I'm having when actually using it is that it can't load the KryptonEffect.xnb file.  I'm aware that MonoGame doesn't have XNA content processors, so I'm compiling the KryptonEffect.fx file in an XNA Content project.

When I try to load the Effect, I get an exception saying The MGFX file is corrupt in the ReadEffect method in MonoGame.  The header should be MGFX but it's a seemingly random byte array.

I then came across this page that says to use a tool named 2MGFX.  I tried this, but the tool reports: The effect must contain at least one technique and pass.  From what I can see from KryptonEffect.fx the file, it does.

Has anyone got the Krypton Lighting Engine working on MonoGame for Windows 8? Or has anyone been able to load any kind of Effect file under Windows 8?


texts: Does destroying body also destroys the sprite?

texts:
Suppose a sprite is attached to a box2d body.
And
world.destroyBody(b); is getting called then the sprite also get destroyed or it stays there in memory.
In my situation lots of box2d bodies are getting created and destroyed and after a delay of few seconds the sprite disappears.
Here's the snippet of where body is getting destroyed:

    @Override
public void act(float delta) {
    super.act(delta);
    camera.update();
    world.step(1/60f, 6, 3);
    if (enemy_destroy) {
        Array<Body> bodies = new Array<Body>();
        world.getBodies(bodies);
        for(int i = 0; i < bodies.size; i++) {
            Body b = bodies.get(i);
            if (b.getUserData() instanceof Boolean) {
                world.destroyBody(b);
                b.setActive(false);
            }
        }
    }
}


texts:
I basically want my camera in 3D move automatically. Currently, I have linear movement which is rather dumb, so I'd like to do a bouncing movement.

However, what is a good equation for bouncing? I mean, for a circle you can do y = sqrt(1 - x^2), but if I were to have a bouncing graph, what would the corresponding formula be? I guess it's something with abs as it has to 'bounce'. Something like (I made this up with Paint):

What is a good equation that results in such a graph? The transformations I can do myself I guess, but I'm just looking for the kind of equation.


texts: What do I need to program games for the PS3?

texts:
Possible Duplicate:
  What do I need to develop for the Playstation 3?

How can an amateur programmer have access to learn programming on PS3, and test the developments on own PS3? Not only use of CPU but also of GPU.


texts:
I have a Direct3D application which uses a PRESENTATION_INTERVAL_ONE implementation. Pity, its blocking and eating my CPU waiting for Present. I ended up searching for raster scan (BitBlt) solutions, sample code from the Internet, but none of them actually worked well - failing to do the exact timing prior to Present call.

Question

So, ideal solution for me would be using PRESENTATION_INTERVAL_ONE (or if its not possible - IMMEDIATE), calling a function

// blabla code
waitForVsync(); //loop here with sleeps or whatever, freeing my CPU
()->Present();  //just in time, no blocking wait, yay!

And upon a return I call Present, which is, lets say, 1ms for _ONE and 0ms for _IMMEDIATE prior to physical top scanline.

I know I am asking a lot and do not hope for a solution in 2011 year, as Microsoft also has failed to improve in this area.

To clarify the issue, I provide a link with a more detailed analysis of a problem:
http://www.virtualdub.org/blog/pivot/entry.php?id=157


texts:
I can't find what is the name of the camera type.

Sided camera view seems logical but not correct thought


texts: Why does this variable keep returning to its original value?

texts:
In my 2D platformer game, I'm trying to create a button that, when the player or a box is on top of it, opens a door of the same color. Here is the code for the button:
extends StaticBody2D

onready var is_object_on_button = false

func _on_Green_Button_Area_body_entered(body):
    is_object_on_button = true
    print("button is down")

func _on_Green_Button_Area_body_exited(body):
    is_object_on_button = false
    print("button is up")

Code for the door:
extends StaticBody2D

onready var is_object_on_button = Green_Button.is_object_on_button
onready var door_collision = $CollisionPolygon2D

func _process(delta):
    if is_object_on_button:
        door_collision.set_disabled(true)
        print("unlocked")
    else:
        door_collision.set_disabled(false)
        print("locked")

The button prints the right things at the right time, so I assume the button is working properly, but the door constantly stays (and prints) locked. How do I fix this?
Edit: After a bit of experimentation, I think that the problem is that is_object_on_button keeps returning to whatever value its assigned at the start: If I set it to true at the onready, it stays true. I do not know how to fix this, either.


texts: Using Lerp to create a hovering effect for a GameObject

texts:
I want to have a GameObject that has a "hovering" effect when the mouse is over it.

What I'm having trouble with is actually having a color that gradually goes from one color to the next.
I'm assuming Color.Lerp() is the best function for that, but I can't seem to get it working properly.

Here's my CubeBehavior.cs's Update() function:

private bool ReachedTop = false;
private float t = 0f;
private float final_t;
private bool MouseOver = false;

// Update is called once per frame
void Update () {
    if (MouseOver) {
        t = Time.time % 1f; // using Time.time to get a value between 0 and 1
        if (t >= 1f || t <= 0f) // If it reaches either 0 or 1...
            ReachedTop = ReachedTop ? false : true;

        if (ReachedTop) final_t = 1f - t; // Make it count backwards
        else final_t = t;

        print (final_t); // for debugging purposes
        renderer.material.color = Color.Lerp(Color.red, Color.green, final_t);
    }
}

void OnMouseEnter() {
    MouseOver = true;
}

void OnMouseExit() {
    renderer.material.color = Color.white;
    MouseOver = false;
}

Now, I've tried several approaches to making it reach 1 then count backwards till 0 including a multiplier that alternates between 1 and -1, but I just can't seem to get that effect. The value goes to 1 then resets at 0.

Any ideas on how to do this?


texts: How do I triangulate non-planar polygons correctly?

texts:
I've got a super simple octagonal mesh with a bevel around the circumference. When I triangulate for export, the cuts form a valley (proper term here?) – which is to say, they transform a level quad into a pair of tris with some degree of concavity.

The resulting normal bake is horrific, as you might expect. Is this a nefarious rookie mistake I've tumbled into?

PS: For reference, here's before:

And here's after:


texts:
I was once told that you should never re-draw a frame if the game logic has not changed since the last draw.

Assuming game logic is updated once every tick, and assuming a game runs at 40 FPS @ 20 ticks/second, does that mean that every two consecutive frames will be exactly the same? If so, is there any visual difference between a game running at 40 FPS @ 20 ticks/second versus a game running at 20 FPS @ 20 ticks/second?

Perhaps I don't understand game loops that well, but it seems to me that ticks/second is a limiting factor of FPS.


texts: Can I debug XNA Xbox 360 games on my PC?

texts: If I made an Xbox 360 game with XNA, would I need to debug it on the Xbox 360 as I was coding it? Or would there be a small emulator on my computer to debug it?


texts: OpenGLHow to fit a texture to a curved plane with GL_CLAMP

texts:
I'm trying to fit a texture on a curved plane made from some triangles  with GL_CLAMP, because GL_CLAMP_TO_EDGE is not available in my OpenGL version, but the texture (512 x 512 pixels) appears so small when render:
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); // If the u,v coordinates overflow the range 0,1 the image is repeated
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // The magnification function ("linear" produces better results)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); //The minifying function

glTexGeni(GL_S, GL_TEXTURE_GEN_MODE,  GL_OBJECT_LINEAR);
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
glEnable(GL_TEXTURE_GEN_S);
glEnable(GL_TEXTURE_GEN_T);

I load the texture like this:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECR );
glTexImage2D(GL_TEXTURE_2D, 0, 4, infoheader.biWidth, infoheader.biHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, l_texture);
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, infoheader.biWidth, infoheader.biHeight, GL_RGBA, GL_UNSIGNED_BYTE, l_texture);


texts: How to rotate vector A around another vector B?

texts:
Lets say I know what is directly above a turret. I also know where the turrets gun is currently pointing. I would like to know where will the turret's gun will point if I rotate it.
I suppose I could multiply \$A \cdot B\$, project \$A\$ on the plane \$B\$ is a normal of and then do the rotation in 2D and add back \$A \cdot B\$ but I am sure the math should be simpler than that?


texts:
I am trying to draw triangles around the screen something like this:

This is my script which can draw 6 triangles but I am not sure how to expand it to draw more like 8 or 10 triangles. Any help is appreciated

using UnityEngine;
using System.Collections;

    public class BackgroundScript : MonoBehaviour
    {
        [SerializeField]
        private Material darkMaterial;
        [SerializeField]
        private Material lightMaterial;

        [SerializeField]
        private float triangleDistance = 50;

        private GameObject[] triangles;

        void Start()
        {
            CreateBackground();
        }

        private void CreateBackground()
        {
            float w = triangleDistance * Mathf.Tan(30 * (Mathf.PI / 180));

            triangles = new GameObject[6];

            for (int i = 0; i < 6; i++)
            {
                GameObject backgroundTriangle = new GameObject();
                backgroundTriangle.name = "triangle " + i;
                triangles[i] = backgroundTriangle;

                MeshFilter mf = backgroundTriangle.AddComponent<MeshFilter>();
                MeshRenderer mr = backgroundTriangle.AddComponent<MeshRenderer>();

                Mesh mesh = new Mesh();
                mesh.vertices = new Vector3[] { new Vector3(0, 0, 0), new Vector3(triangleDistance, 0, w), new Vector3(triangleDistance, 0, -w) };
                mesh.normals = new Vector3[] { new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0) };
                mesh.triangles = new int[] { 0, 1, 2 };
                mf.mesh = mesh;

                mr.material = i % 2 == 0 ? darkMaterial : lightMaterial;

                backgroundTriangle.transform.Rotate(new Vector3(0, i * 60 + 30, 0));
                backgroundTriangle.transform.SetParent(this.transform);
            }
        }
    }


texts: Blender 2.6: How to Undo 3D Cursor Movement

texts:
I sometimes place the 3D cursor at the wrong location by a undesigned click on the left mouse button.

But when I'm trying to click Control + Z in order to undo the accidental 3D cursor movement, it doesn't revert.

So my question is: Is there an easy way to get Blender's (2.6) 3D cursor back to it's previous location? Thanks.


texts: Unity - unable to play audio clips simultaneously from within a coroutine

texts:
I am using Unity 2017.3.1f1. I have created a co-routine for a car engine controller which would play a car start sound once, and while it is fading, it would start a looping sound that would gradually increase its volume while the start sound is still playing. Here is what I have written:

     public virtual IEnumerator PlayEngineSounds()
     {
         float playtimeStarted = Time.unscaledTime, startSoundLength = startSound.clip.length;
         startSound.Play();
         if (loopSound == null)
         {
             yield return new WaitUntil(() => startSound.isPlaying);
         }
         else
         {
             while (startSound.isPlaying)
             {
                 var percent = (Time.unscaledTime - playtimeStarted) / startSoundLength;
                 loopSound.volume = percent*_loopSoundMaxVolume;
                 Debug.Log("Loopsound % = " + percent, this);
                 yield return null;
             }
             loopSound.volume = _loopSoundMaxVolume;
             yield return null;
         }
     }

Basically I am taking the percentage of the start sound and I use that for the level of the loop sound. The more completely the start sound is played, the louder the loop sound should get.

What I observe, is that my logged messages appear correctly in time, but the volume level of the loop sound is not affected. Then, when the start sound completes, the loop level gradually increases its volume. It behaves as if the volume updates are "delayed" and executed after the start sound is finished, instead of playing both simultaneously.

The startSound and loopSound are separate AudioSource components, that reside in different game objects within the hierarchy of my vehicle. I am invoking the PlayEngineSounds corouine from my Start method like this:

internal void Start()
{
    StartCoroutine(PlayEngineSounds());
    // other code ...
}


texts: reading input from multiple mice in QB64 in Windows 10?

texts:
I am looking to write a non-network multiplayer game for Windows 10 with QB64 that accepts input from 2 or more USB mice plugged into the system. Like a simple Pong game where additional players plug mice into a USB hub to use as game controllers.
I have been googling this and found some older threads

Is it possible to detect two different mice at the same time, and have their movements recorded seperately? Asked 8 years, 9 months ago
How do I read input from multiple keyboards/mice on one computer? Asked 7 years, 6 months ago

however these are pretty old threads from before Windows 10, also they seem to be more oriented towards C++ or .NET.
Can anyone provide some example how it might be done with QB64 under Windows 10?
Thanks


texts: Develop on Oculus Go using Java and OpenGL

texts: I have recently done some game development using Java and OpenGL (with the JOGL library), and I was thinking about trying to learn how to develop on an Oculus GO. However, all guides seem to assume that the developer is going to use Unity. Is it possible to develop Oculus GO applications with Java and OpenGL directly? Is there any good documentation or guides for this?


texts: Why does RenderTarget2D only output a black texture after a few seconds?

texts:
I encountered this strange problem where my UI drawing to RenderTarget2D
works for a couple seconds and then suddenly goes black.

This is the RenderTarget2D function:

public RenderTarget2D RenderUi(SpriteBatch spriteBatch) {
    RenderTarget2D renderTarget = new RenderTarget2D(Graphics, 1920, 1080);
    Graphics.SetRenderTarget(renderTarget);

    Graphics.Clear(Color.Transparent);

    spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default);

    /* Goes black even if commented out
     - My draw calls
    */

    spriteBatch.End();

    Graphics.SetRenderTarget(null);

    return renderTarget;
}

And this is the Draw function:

public virtual void Draw(GameTime gameTime) {
    RenderTarget2D uiRenderTarget = UserInterface.RenderUi(SpriteBatch);

    /* Main SpriteBatch */
    SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.PointClamp,
        null, null, null, Camera.TransformMatrix());

    World.Draw(gameTime, SpriteBatch);
    Entities.Draw(gameTime, SpriteBatch);

    SpriteBatch.End();

    /* Ui SpriteBatch */
    SpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.Default);
    if (Input.IsAction(Actions.DrawUI))
        SpriteBatch.Draw(uiRenderTarget, new Rectangle(0, 0, Graphics.GraphicsDevice.Viewport.Width, Graphics.GraphicsDevice.Viewport.Height), Color.White);

    SpriteBatch.End();
}

So if I hold down the DrawUI button the UI draws correctly and everything below but then it suddenly goes black, releasing the button shows that everything but that RenderTarget still draws fine.

Why does this happen and what can I do to avoid that?


texts: What is the benefit of a sparse bindless texture array over just bindless textures?

texts:
I've seen the talks on AZDO, and they tend to suggest moving towards an architecture where you have one texture array per texture "shape". This is sparse, so you allocate loads of layers for potential future texture loads, and then commit each layer as you load a texture to it. You then make the whole thing bindless, and you can now pass a handle & layer to your shaders for texturing.

This is great, but what has it bought me above just using bindless textures? With bindless textures I seem to have to do exactly the same amount of work - in fact, a little less: I just pass in the texture handle (or sampler handle) to my shader.

So why the push for sparse bindless texture arrays?


texts: OpenGL : sluggish performance in extracting texture from GPU

texts:
I'm currently working on an algorithm which creates a texture within a render buffer. The operations are pretty complex, but for the GPU this is a simple task, done very quickly.

The problem is that, after creating the texture, i would like to save it.
This requires to extract it from GPU memory.

For this operation, i'm using glGetTexImage(). It works, but the performance is sluggish. No, i mean even slower than that. For example, an 8MB texture (uncompressed) requires 3 seconds (yes, seconds) to be extracted. That's mind puzzling. I'm almost wondering if my graphic card is connected by a serial link...

Anyway, i've looked around, and found some people complaining about the same,
but no working solution so far. The most promising advise was to "extract data in the native format of the GPU". Which i've tried and tried, but failed so far.

Edit : by moving the call to glGetTexImage() in a different place, the speed has been a bit improved for the most dramatic samples : looking again at the 8MB texture, it knows requires 500ms, instead of 3sec. It's better, but still much too slow. Smaller texture sizes were not affected by the change (typical timing remained into the 60-80ms range).

Using glFinish() didn't help either. Note that, if i call glFinish() (without glGetTexImage), i'm getting a fixed 16ms result, whatever the texture size or complexity. It really looks like the timing for a frame at 60fps.

The timing is measured for the full rendering + saving sequence. The call to glGetTexImage() alone does not really matter. That being said, it is this call which changes the performance.

And yes, of course, as stated at the beginning, the texture is "created into the GPU", hence the need to save it.

Edit 2 : I've also tried to use glReadPixels(), instead of glGetTexImage(). But it's worse unfortunately. Approximately twice slower.

Edit 3 : Here is the code. Note that it uses a "framework" that i've not developed. So some of the function calls here are not OpenGL standard. But they are nonetheless quite self-expressive.

glDisable(GL_BLEND);

// Simple construction, for test : the resulting texture is output into render buffer
renderbufx1.bind();
    clear(0,0,0,0);
    simpleDiffShader.bind();
    simpleDiffShader.setTexture("TextureRef",img.tex,0);
    simpleDiffShader.setTexture("TextureDown",renderbufx2.getTexture(),1);
    img.tex->drawPart(-1,-1,2,2,0,0,1,1);
    simpleDiffShader.unbind();
renderbufx1.unbind();

// Not really useful, but just in case, the result is copied into another render buffer.
// renderbufx1 is going to be displayed, and i want to avoid any access conflict
savebufx1.bind();
    clear(0,0,0,0);
    renderbufx1.getTexture()->bind();
    renderbufx1.getTexture()->drawPart(-1,-1,2,2,0,0,1,1);
    renderbufx1.getTexture()->unbind();
savebufx1.unbind();

savebufx1.getTexture()->bind();
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_BYTE, t.data);  // <-- This is the line
savebufx1.getTexture()->unbind();

glEnable (GL_BLEND);

renderbufx1.getTexture()->bind();
renderbufx1.getTexture()->drawPart(tex2x,-1,w,h,texSpan,texSpan,fact,fact);
renderbufx1.getTexture()->unbind();

Timing measured encompasses all this (and a few other things, which do not really contribute to the total).

Edit 4 : (on course for the most edited question of the week)

The native texture format of the GPU is supposed to be retrieved through the function glGetTexLevelParameter. More precisely, i've used this line of code :

glGetTexLevelParameteriv ( GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &iTexFormat);

The result of the function (within iTexFormat) is 32856.
32856, decimal, is 0x8058, and within gl.h there is :

#define GL_RGBA8 0x8058


texts: Unity Inspector - Turn off script for a group?

texts:
I have a large group of objects in Unity that can be grouped and for one instance I want to turn off a script on each one, for over 100 this can be tedious, can this be done group wise within the inspector? Instead of me going into each one and manually turning a script off?

I have tried doing this within a script but it will not work for this situation.


texts: limiting jump forces to achieve a maximum jump height

texts:
A player and the world are modeled using a physics engine.  Jumping is modeled by applying a vertical upward force to the player's physics body when the jump button is pressed.

The upward force is being applied every update tick that the button is held. This makes the player accelerate upward so long as the button is held, potentially forever, rather than limiting the jump to a predetermined maximum jump height

How can this be fixed so that pressing the jump button allows a limited jump height, even if the button is held down indefinitely?


texts: In My Direct2D Gui System, Is It Safe To Use A Bitmap Render Target Per Gui Element?

texts:
I am trying to implement a relatively simple GUI system for use in a few simple games.

In this system, all Gui elements extend BaseControl. BaseControl has an update and draw method, as well as various parameters applicable to all controls (clipping, transforms, etc).

Let's say I have a Panel element, which contains other elements. The panel element will pass all its children a render target when it wants them to draw themselves.

There is a button that exists partially outside the bounds of the panel. If clipping is enabled in the panel, that button should show up clipped at the panel boundary. The button doesn't know it is out of bounds of its parent, nor should the button have to check if it needs to be clipped, or if clipping is enabled, or if a specific transform should be applied to it, etc.

Here's how I was going to go about handling clipping and other effects that should be controlled by the BaseControl class and not derived controls. Each control has an ID2D1BitmapRenderTarget, and they draw what they want onto it. When the BaseControl's internal Draw method gets what the derived control drew to it, it can modify it, get a Bitmap from its render target, and draw the bitmap to the parent's target.

So for example, if the parent is that panel with clipping enabled, it can perform any clipping on its internal Bitmap (which its children have drawn onto) before drawing that onto the window render target. Button draws to its own render target. Get bitmap from button's render target that is drawn to the Panel. The panel gets the bitmap from its render target, and clips the bitmap before drawing the contents to the window render target.

Right now, everything is drawing to a single render target (the window's render target). The problem is, once something is drawn to it, that drawing can't be editted. So if the internal draw method of a BaseControl, for example, had properties set to clip whatever the derived code drew, it would have no way to clip the now already drawn image without affecting other GUI controls or content drawn by other parts of the game.

Is it safe to have potentially a lot of ID2D1BitmapRenderTarget instances like this (there would be 1 for every control)? Is it as safe to make a lot of ID2D1BitmapRenderTargets as it is to make an ID2D1SolidColorBrush per control? Or is there a much better, more common sense way to accomplish what I'm trying to do that would only use one render target?


texts: How to create a "border" effect in Unity?

texts:
Okay let me start off by saying I have searched for several days on this topic, and it seems that either nobody posted anything about it, or it is on the internet, but too far buried under piles of useless information for me to find. I have created a custom terrain algorithm in Unity and have built a parser to read provinces onto the map.

The short version description of the parser is that it goes into the assets folder, finds "map/provinces.png", reads the borders of the provinces as vertices, reads "map/height.png" to determine the height of the visual terrain, and reads "map/terrain.png" to determine how much of each province is of each terrain (for example, Paris can be 95% urban, and 5% forest in my setup).

I want to make each and every one of the 500 european provinces start with a player. The idea is that the players will fight small-scale wars for 30-40 turns, by which point most or all small players will be absorbed into the most successful players country. These will then fight for 60-80 turns for dominance, with alliances being forged and broken and countries being destroyed. The problem is described below;

Each player has his own unique color. Many of the players will obviously have similar colors, and I do not want 2 dark red countries bordering eachother without some easy way to see the border. I want to basically draw a line in between any two provinces that belong to different players and border each other. I am having trouble finding a way to easily do this, as my current solution tests all provinces if they border foreign provinces, and runs a rather expensive test on each of the bordering provinces vertices to see if they border eachother, then stores those vertices as vectors and draws a line from each vertex to its others.

I have considered using a shader to accomplish this, but was unsure if that was the right approach and whether or not that would (or could?) be more efficient.


texts: Playing a video in AR using Vuforia and Unity 5

texts: I am trying to play a video in augmented reality using Vuforia and Unity5. I followed a few videos but I am still not able to play it. Can anybody help? I get the "error texture icon" instead of the play icon.


texts: Handling collisions with objects that use vector of unique pointers

texts:
#pragma once
#include "Entity.h"
#include <iostream>

class Projectile : public Entity
{
public:
    Projectile() {}

    Projectile(float x, float y) {
        load("Graphics/Projectile.png");
        m_sprite.setPosition(x, y);
        m_speed = 400;
    }
};

#pragma once

#include "Entity.h"
#include <iostream>
#include "Projectile.h"

enum class Color {
    red,
    yellow,
    brown,
    blue
};

class Enemy : public Entity
{
public:
    Enemy(const Color& c, const sf::Vector2f& pos) {
        switch (c) {
            case Color::blue:
            {
                load("Graphics/blueEnemy.png");
            }
            break;
            case Color::red:
            {
                load("Graphics/redEnemy.png");
            }
            break;
            case Color::yellow:
            {
                load("Graphics/yellowEnemy.png");
            }
            break;
            case Color::brown:
            {
                load("Graphics/brownEnemy.png");
            }
            break;
        }
        setPos(pos);
        m_speed = 100;
    }
};

  #pragma once
    #include "Entity.h"
    #include "Projectile.h"
    #include <vector>

class Spaceship : public Entity
{
public:
    Spaceship();
    void move(float);
    void shoot(float);
    void update(float);
    void draw(sf::RenderWindow*) override;
private:
    bool wasSpacePressed;
    std::vector<std::unique_ptr<Projectile>> m_projectiles;
    sf::Clock m_clock;
};

class EnemyFleet : public Entity
{
public:
    EnemyFleet();
    ~EnemyFleet();
    void move(float);
    bool isEnemyBottom() const;
    bool isLeftMost() const;
    bool isRightMost() const;
    void moveX(float);
    void moveDown();
    void update(float);
    void draw(sf::RenderWindow*) override;

private:
    std::vector<std::unique_ptr<Enemy>> m_enemyFleet;
    bool m_leftToRight; //motion of the enemyfleet
    float m_speedModifier;
};

I want to be able to delete a projectile and enemy when they collide with each other, but I'm not sure how to do this since unique_ptr cannot be copied into any parameter in some collision manager class bc it has exclusive ownership. Is unique_ptr still something i should use bc i dont have to call delete (like if its a raw ptr)?


texts: how to create an outlined polygon with vector3 coordinates?

texts:
I have a set of vector3 coordinates and I use them to draw a polygon in another app, my question is: how can I calculate a second set of coordinates to make it look like the line is outlined.

in the above picture, the blue dots are the vector3s I have and the red dots are the one I need, can anyone help me with an algorithm or formula to calculate them?
thanks


texts:
I'm trying to draw 4 lines above map cells as cells access level using this code

VertexPositionColor[] collection = new VertexPositionColor[]
{
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[0].X, loc.Y + _cellPoints[0].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[0].X, loc.Y + _cellPoints[0].Y, 0f), color),

    new VertexPositionColor(new Vector3(loc.X + _cellPoints[1].X, loc.Y + _cellPoints[1].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[1].X, loc.Y + _cellPoints[1].Y, 0f), color),

    new VertexPositionColor(new Vector3(loc.X + _cellPoints[2].X, loc.Y + _cellPoints[2].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[2].X, loc.Y + _cellPoints[2].Y, 0f), color),

    new VertexPositionColor(new Vector3(loc.X + _cellPoints[3].X, loc.Y + _cellPoints[3].Y, 0f), color),
    new VertexPositionColor(new Vector3(loc.X + _cellPoints[3].X, loc.Y + _cellPoints[3].Y, 0f), color),

};

_vertexBuffer = new VertexBuffer(_device, VertexPositionColor.VertexDeclaration, 8, BufferUsage.WriteOnly);
_vertexBuffer.SetData(collection);

Device.SetVertexBuffer(_vertexBuffer);
Device.DrawPrimitives(PrimitiveType.LineList, 0, 4);

but it gives on this error

  An error occurred while preparing to draw. This is probably because the current vertex declaration does not include all the elements required by the current vertex shader. The current vertex declaration includes these elements: SV_Position0, COLOR0.

in

Device.DrawPrimitives(PrimitiveType.LineList, 0, 4);


texts: Name of the model in memory that you use for map collision detection?

texts:
I'm trying to remember the English name for a memory model of a map built exclusively for handling collision detection. I think this is especially frequent in tile-based platform games.

I believe the Spanish term for it is "Mapa de durezas".

If you have a Super Mario tilemap like this:

    C     +        'P' = Pipe
         +++       '+' = Brick
        +++++      '@' = Ground
   P   +++++++     'C' = Cloud
 @@@@@@@@@@@@@@@@  ' ' = Air

Then the <ENGLISH EXPRESSION THAT I'M LOOKING FOR> of that map would be:

          *       '*' = Solid
         ***      ' ' = Traversable
        *****
   *   *******
 ****************

Any clues?


texts: What are the benefits of using a 2D game engine on Android?

texts:
I have thought about just coding a 2D game on Android using just pure Java and the Android SDK, no engines like libdgx, cocoa-2dx attached. I don't know if I really need to use a game engine or not. Doesn't Java already come with basic libraries and APIs for most things already?

I'm not interested in the cross-platform aspect of game engines. The game is 2D, so there's no complex issues with 3D, importers, or what not. I also don't like to have to code around level editors or pre-built constructs like a character or tile class.

Given this, are there any other benefits for me using a game engine to code my Android 2D game? For example, I'm clueless with OpenGL so if I'm doing it w/o an engine I would be using pure Java, would that be significantly slower than using an engine like libgdx?


texts: Architectural approaches to creating a game menu/shell overlay on PC/Linux?

texts:
I'm am working on a collection of games for a custom digital tabletop installation (similar to Microsoft Surface tables). Each game will be an individual executable that runs full-screen. In addition, there needs to be a menu/shell overlay program running simultaneously. The menu/shell will allow users to pause games, switch to other games, check their game history, etc.

Some key requirements of the shell:

it intercepts all user input (mainly multitouch) first before passing it on to the currently running game (so that it can, for instance, know to pop-up at a "pause" command);
can reveal on arbitrary portions of the screen, with the currently running (but presumably paused) game still showing underneath, ideally with its shape/size being dynamic, to allow for creation of an animated in/out drawer effect over the game.

I'm currently looking into different architectural approaches to this problem, including Fraps and DirectX overlays, but I'm sure I'm missing some ways to think about this. What are the main approaches I should be considering?

(Note the table is currently being run by Windows PC, but it could potentially be a Linux box instead. By this I don't mean I need an OS-agnostic solution. I'd be happy with a Windows-specific solution. But I would be willing to consider switching to Linux and using a Linux-specific solution if it's much easier to achieve this in Linux.)


texts: How to make healing in an exploration game interesting

texts:
I'm creating a game with a heavy focus on exploration, though I'm at a bit of a loss for healing.

The problem is that I don't like the idea of enemies randomly dropping health, as this usually results in grinding when at low health and not near any healing stations(Metroid, Axiom Verge), and I don't want to copy the Soul/Focus system from Hollow Knight(Combat system has already been stolen by me :3), but Hollow Knight is the only game I've played with a focus on exploration that made healing interesting.

I've also thought of auto-regeneration, however that can easily lead to the player cowarding during a boss fight while they heal, and that would break the flow of the gameplay.

I've also considered something like striking a foe heals 1/8th of a health point, however this leads to the player feeling less tense after they take a gain 1/8th which will keep them from dying if they get hit again, and it makes the game feel like its all offense and little defense.

I've also though about an items approach where the player has to eat something or drink something to heal, however this doesn't really encourage healing as once you run out of items, you can no longer heal until you get some more(Legend of Zelda).

I've also though about no healing at all, however I noticed that when exploring and then you take a dumb hit before a hard boss, or a dumb hit before the boss gets hard(cough Cuphead cough), the player will just either commit suicide or run back to a healing station.

What can I do to make healing interesting, and not break the flow of gameplay?

This is a 2D platformer, and jumping is really important in the combat.


texts: Mouse drag rotation script doesn't work when attached to OBJ model

texts:
I am new to Unity. I imported an OBJ model and assigned materials to it.

I want to rotate it using the mouse in the game, using this script:

using UnityEngine;

public class MouseDragRotate : MonoBehaviour {
    float rotationSpeed = 0.2f;

    void OnMouseDrag()
    {
        float XaxisRotation = Input.GetAxis("Mouse X")*rotationSpeed;
        float YaxisRotation = Input.GetAxis("Mouse Y")*rotationSpeed;
        // select the axis by which you want to rotate the GameObject
        transform.RotateAround (Vector3.down, XaxisRotation);
        transform.RotateAround (Vector3.right, YaxisRotation);
    }
}

I tried to apply this rotation script to the OBJ asset in my Project folder, but I wasn't able to find an Add Component option in its Inspector.

So I dragged it to the Hierarchy panel to create an instance of the object in my scene. I applied my materials again to this instance.

Then I added the rotation script using the Add Component button in the Inspector.

But when running the game in play mode, I can't rotate it.

I verified that the script above works perfectly for the default Cube or Plane primitives in Unity, but not for this imported object.

How can I make this script work with my OBJ model?


texts:
I want to make a 2D Point Light in XNA, I was able to find some helpful information but it is too advance for me, since i know nothing about Shaders

http://www.soolstyle.com/2010/02/15/2d-deferred-lightning

So my best aproximation is use a texture and use alpha blending, but im not happy with this result.

So I was wondering, what is the most simple method to make a simple 2d point light? I'd rather code examples.


texts: How to create pixel-perfect text in TextMeshPro with a shadow?

texts:
Problem
Making the font asset of type Raster creates a pixel-perfect font, but it doesn't have the underlay option inside its material to give it a shadow.
Making it of type SDF (or one of the variants) does, but it's blurred in game view.
See the image for a visual example. The top text uses the SDF variant, whereas the bottom is of Raster type. This is Game View, zoomed in.

Attempted Solution
I considered using Unity's own Text component, which, strangely enough, doesn't blur in Game View (but does in Scene View). However, to give it a shadow, I need to create a 2nd, black Text object to place behind it with a small offset. This is fine, but then I need to match its value to the main Text's, and I can't seem to do that without checking every frame inside Update(), which is wasteful.


texts: Smoothly fitting texture tiles using alpha gradient on edges

texts:
I'm trying to draw a background texture with tiles that I'll rotate and mirror to create a maze. Here is a sample tile:

As you can see, I use an alpha gradient on the borders. If I'd use a sharp border instead, you'd notice the border between a tile and another because these shadows and glows are not perfectly symmetrical.

So far it works OK, but I've noticed there is a slightly darker spot where two tiles connect:

I used Photoshop to create these gradients, and was very careful to make sure these gradients are linear and start exactly where the next gradient ends, so that the total alpha of every pixel add up to exactly one.

I'm using a SpriteBatch to draw these textures and use the default blending mode (I don't set any blend function at all). Apparently I'd need some blending function whose output will be the sum of both image's alphas and the average of their colors. Is this the default mode (if so, I guess my picture's alpha gradients are not perfectly linear)? And if not, what should I set my SpriteBatch's blend function to?

Edit: So I tried batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_DST_ALPHA) and it fixed the dark spot, but now the textures I draw on top look messed up, even if I revert it back to the old blending mode right after drawing my tiles.


texts:
I am wondering what the best way to make a random set of 2D textures. Currently I have tried the follow code but I am aware that when this comes to collisions that would be an issue. Therefore I would really appreciate a different method of achieving this.

Random random = new Random();
        for (int i = 0; i < 10; i++)
        {
            GenPos = new Vector2((800 + (Length * Stone.Width)), (500 - (i * Stone.Height)));

            int number = random.Next(1, 3);

            if (i == 9)
            {
                if (Length < 31)
                {
                    i = 0;
                    Length++;
                }

            }
            else if (number == 1)
            {
                spriteBatch.Draw(Stone, GenPos, Color.White);
            }
            else if (number > 1)
            {
                spriteBatch.Draw(Grass, GenPos, Color.White);
            }

        }

This code works except for two critical things, the collision detection method dose not work as the GenPos changes throughout the code and that the Stone and Grass flashes. Also note that the grass is just a place holder for a future texture of Iron_Ore. I am wondering what the best method for achieving this would be because I need it to be able to detect collisions using a similar detection method to:

public Boolean StonePlayerCollision()
    {
        if (playerPosition.Y >= (StonePosition.Y + Stone.Height) && playerPosition.Y <= StonePosition.Y ))
        {
            return true;
        }
        else
        {
            return false;
        }

    }

If you are to suggest a new method, which would be much better than maintaining this messy system please note that the Tiled area will need to be in the view matrix method as seen below:

spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
            SamplerState.LinearWrap, null, null, null, camera.ViewMatrix);

I hope that someone will be able to suggest the best / most efficient way of making a randomly tiled textures that can be detected by collisions.
Thank You.


texts:
I have a method here that returns true if a collision is detected between the player and tile.

            private bool CheckCollision()
    {
        foreach (CollisionTile tile in map.CollisionTiles)
        {
            if (tile.TileType == "stone" && player.rectangle.Intersects(tile.Rectangle))
            {
                return true;
            }

            if(tile.TileType == "water" && player.rectangle.Intersects(tile.Rectangle))
            {
                return true;
            }
        }
        return false;
    }

The collision detection works fine but when I try to move away from the tile I don't move at all. What could be my problem here?

              if (!CheckCollision())
        {
            player.Update();
        }

this is in my update method.


texts: In collision detection/resolution, what is a "collide and slide" algorithm?

texts:
Can anyone help me to better understand the concepts behind this algorithm?
I've seen this phrase come up several times during my research into creating a 3D character controller, but am having issues finding much information about it. One example is from a user manual that accompanies a character controller asset on the Unity asset store.
I'm used to handling collisions in 2D that involve primitive colliders, so most of the time I simply move my entity, check for overlaps, and then calculate the shortest distance out of the primitive (if one is using Unity, he or she can also use the ColliderDistance2D API for this). It seems like "collide and slide" might be a bit more involved, especially in 3D where contact with a mesh may be the norm instead of contact with primitives. From the manual I linked earlier it seems that an entity's movement vector is altered based on the normal of the surface with which that entity collides, but where does the actual collision (overlap) occur, and how do we resolve it?


texts: How to get the path of a file after publishing my game

texts:
I made a "game" for a college project that reads data from .txt file at startup and draws some models according to the data in that file. This is the code I use

using (StreamReader sr = new StreamReader(@"C:\Users\User\Desktop\Linije.txt"))
                {
                    String linija;
                    while ((linija = sr.ReadLine()) != null)
                    {
                        red = linija.Split(',');
                        model = red[0];
                        x = red[1];
                        y = red[2];
                        z = red[3];
                        elementi.Add(Convert.ToInt32(model));
                        podatci.Add(new Vector3(Convert.ToSingle(x),Convert.ToSingle(y),Convert.ToSingle(z)));
                    }
                }

As you see, this code fills some variables that are then used to define the model that will be drawn and the coordinates where it will be drawn.
The problem that I'm having is that I don't know how to distribute that file to other computers (obviously on another computer it would have another path)? Do you have some advices on how to do this?
P.S I tried to put it in the Content and set the Build Action on None, and I can see the file in the content directory, but when I change it, nothing happens (the models don't change as they should)


texts: Enemies are penetrating in each other when following player

texts:
As you can see the image my enemy (when following my player), penetrate each other. How can i avoid it? I am using NevMeshagent to follow the player.

void Update () {
    currentNavMeshAgent.destination = player.transform.position;
}

I have added a Rigidbody and a Collider to my enemy object but they are still penetrating each other


texts: Best 2D graphics API when the only functionality needed is writing individual pixels to the framebuffer

texts:
I have been dreaming for years about programming a relatively simple, but from the standpoint of the game engine, a very unusual 2D game engine for the PC platform. I am planning to use either C or C++ for the core engine, and maybe later expose the engine to a scripting language such as ruby, python or lua (for higher level programming of the content of the game). Not having ever programmed any noteworthy GUI applications let alone games, i am not really sure about which API:s to select for the task.

The requirements for the API:s are unlike other 2D games, since instead of drawing sprites, glows etc. using OpenGL, Allegro or SDL, i only need to be able to open a window instance, clear the framebuffer, write individual pixels to it, and then draw everything to the screen. Thus the API needs to be really really fast, and no additional functionality is needed from the API.

Additionally i need user input and sound output, through an additional API if necessary.
Do you have any suggestions for the best course of action?


texts: XNA renderTarget, how to convert mouse coordinates to world position when upscaling

texts:
I'm currently developing a monogame game with a tile engine.

I have been experimenting with different tiles and sprites sizes : 16px, 32px, 64px
I have settled for 32x32 pixels tiles rendered at a 64x64px size on screen.

I have read that a good way to do so is to use a RenderTarget2D. I've done so. It works well. I'm using
SamplerState.PointClamp to keep the pixel aspect clean.

So for a 1440x900 resolution I use

 renderTarget = new RenderTarget2D(graphics.GraphicsDevice, 720, 450);

My question : when using the RenderTarget2D to upscale the screen, it logically messes up the camera I had working, and even more so the conversion of mouse coordinates to world coordinates.
How should I modify the camera and the "mouse coordinates" to world position function. Is it even possible to convert properly mouse coordinates when you are upscaling everything with a renderTarget ?

Screenshot

This answer hints that it may be problematic, can somebody explain to me why ?

From the link :
so if your graphics aren't dependant on other graphical features like a mouse, then I would use a RenderTarget

I can't find any resources about this. I always find a solution by myself, but this one is too much for me. Linear algebra is not my strong suit. Thank to anybody who can help.

My transform Matrix and Worldposition conversion

public Matrix Transform(GraphicsDevice graphicsDevice)
{
    m_Transform =

      Matrix.CreateTranslation(new Vector3(-m_CameraPosition.X, -m_CameraPosition.Y, 0)) *
         Matrix.CreateRotationZ(Rotation) *
         Matrix.CreateScale(new Vector3(Zoom, Zoom, 0)) *
         Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));

    return m_Transform;
}

public Vector2 Worldposition(GraphicsDevice graphicsDevice, Vector2 position)
{
    //Invert camera
    Matrix m_InvertTransform =
    Matrix.CreateTranslation(new Vector3(-(m_CameraPosition.X + ViewportWidth * 0.5f), 0, -(m_CameraPosition.Y + ViewportHeight * 0.5f))) *
    Matrix.CreateRotationZ(Rotation) *
    Matrix.CreateScale(new Vector3(Zoom, Zoom, Zoom)) *
    Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, 0, ViewportHeight * 0.5f));
    m_InvertTransform = Matrix.Invert(m_InvertTransform);
    //Transform the position
    Vector3 newPos3 = Vector3.Transform(new Vector3(position.X, 0, position.Y), m_InvertTransform);
    return new Vector2((newPos3.X - 720) , (newPos3.Z - 450) );
}

Edit :

In my Update() method :

Vector2 vector = new Vector2((int)player.X, (int)player.Y);
camera.ChangePosition(GraphicsDevice, vector);

The ChangePosition function in my Camera Class
    public void ChangePosition(GraphicsDevice graphicsDevice, Vector2 newposition)
    {
     m_CameraPosition = newposition;
    }


texts: How can I convert a rigidbody velocity value to some normal reading speed value?

texts:
void Update()
    {
        var vel = rigidbody.velocity;
        movementSpeedUiText.text = vel.ToString();

The result is :

what I understand from this ? what is the speed ? I don't want to know only if the player is moving or not but what is the speed.  what I see is some vector3.
This is the complete script :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerSpeedDistanceController : MonoBehaviour
{
    public GameObject target;
    public GameObject speedArea;
    public float speed;
    public Animator animator;
    public Text movementSpeedUiText;
    public Text distanceFormTargetUiText;
    public Text playerDirectionUiText;

    private float distance;
    private Rigidbody rigidbody;
    private Vector3 lastPosition;
    private bool isMoving;

    // Start is called before the first frame update
    void Start()
    {
        lastPosition = transform.position;
        isMoving = false;

        rigidbody = GetComponent<Rigidbody>();

        movementSpeedUiText.text = animator.GetFloat("Forward").ToString();
        distanceFormTargetUiText.text = Vector3.Distance(transform.position, target.transform.position).ToString();
        playerDirectionUiText.text = transform.forward.ToString();
    }

    // Update is called once per frame
    void Update()
    {
        if (isMoving == false)
        {
            movementSpeedUiText.text = "0";
        }
        else
        {
            movementSpeedUiText.text = animator.GetFloat("Forward").ToString();
        }
        distanceFormTargetUiText.text = Vector3.Distance(transform.position, target.transform.position).ToString();
        playerDirectionUiText.text = transform.forward.ToString();

        if (transform.position != lastPosition)
            isMoving = true;
        else
            isMoving = false;

        lastPosition = transform.position;
    }
}

because the player have animator and also some more animators on the childs the movement speed is affected by this animators. even if the player is not moving he is still looks like moving when calculating the speed.
"Forward" is parameter of the HumanoidWalk speed so when I press the W key and the player is moving it's showing the value of the "Forward" parameter.
and because when the player is not moving I don't press on W or any other key it's showing in the movementSpeedUiText text some E long number.
That's why I added the part that detect if the player is moving or not and if not I assign "0" to the text.
The problem now is when I press on the W key and move the player the text is stuttering flickering.


texts: How can I make a coroutine run for a specific number of times in Unity?

texts: I use coroutines in unity, with while(true) condition, which runs it indefinitely. I need to make the coroutine run for a specific number of times, let's say 10 times. Any pointers will be much appreciated!


texts:
I'm going mad to clamp rotation of an object.

I've tested using Inspector that correctly rotation range is Z>-15 and Z<30.

I've written this code but it isn't working properly !

if (rb.transform.rotation.eulerAngles.z > 30)
    rb.transform.Rotate (-Vector3.forward * speedTurretMovement  , Space.Self);
if (rb.transform.rotation.eulerAngles.z < -15 )
    rb.transform.Rotate (Vector3.forward * speedTurretMovement , Space.Self);

Thanks


texts: 3D Dice using Maya - for integration with iOS game app

texts:
My designer is building a 3D design of a dice using Maya.

I want to integrate this in my iOS app so that the user can spin the dice and get a number. Then they play the game using that number.

So, I have two questions:
1) How can I make the dice spin and stop at a random position so that a number is presented to the user?

and

2) Once it stops spinning how can I detect the number that is displayed to the user (programmatically)?

Many thanks.
-Anil


texts: ObjectDisposedException when Texture2D isn't disposed

texts:
I'm making a particle engine so I develop a texture programatically and I want to display it in a Windows Form picture box.  So I create the Texture2D which goes fine.  Then I use this code to convert from a Texture2D to an Image for the picture box.

    public static System.Drawing.Image Texture2Image(Texture2D texture)
    {
        if (texture.IsDisposed)
        {
            return null;
        }

        MemoryStream memoryStream = new MemoryStream();

        texture.SaveAsPng(memoryStream, texture.Width, texture.Height);

        memoryStream.Seek(0, SeekOrigin.Begin);

        System.Drawing.Image image = System.Drawing.Bitmap.FromStream(memoryStream);

        memoryStream.Close();
        return image;
    }

I get the error at the texture.SaveAsPng(...).  It says 'Cannot access a disposed object. Object name: 'Texture2D'.'
But as you can see, I just checked to make sure it wasn't disposed.  I looked at the Locals info which also says the IsDisposed flag is false.  No where in my code to I call texture.Dispose() or anything of the sort.  I have no idea where this error is coming from.  Any help would be greatly appreciated, thanks in advance.


texts: Bullet direction incorrect around sphere

texts:
Here is a little background on how my game objects are set up, and how the rotations and firing bullets work. I am working on this game in Unity.

I have two game objects that orbit a sphere (for simplicity lets say the player is a space ship and the enemy is a UFO). The UFO shoots at the ship in a spherical manner around the surface of the sphere (my intention at least).

The ship and UFO both have a parent game object that is located at the center of the sphere, and each are moved back on the z-axis by 10 units. All of the movement rotations are applied to the parent pivot points which causes the two objects to orbit freely in any direction as the pivot points rotate.

In this previous question I received some help to get my bullets to fire from the UFO towards the ship. The solution provided works great, the UFO always fires bullets towards the ship as the ship flies around. Once both objects move to opposite side of the sphere (past 180 degrees from the original starting point) the direction to fire the bullet seems mirrored. As the ship flies around the, the bullets fly in a mirrored direction.

Here is how I am rotating the bullets (note: I use the same pivot point technique as stated above for the bullets as well):

When shooting a bullet I first I generate a direction vector like so:

var ufoSpoke = ufo.transform.position - Vector3.zero;
var shipSpoke = ship.transform.position - Vector3.zero;
var pointOut = Quaternion.LookRotation(ufoSpoke, -shipSpoke);
var pointOnShortestArc = pointOut * Quaternion.Euler(90f, 0, 0);
var direction = (pointOnShortestArc * Vector3.right).normalized * 50f;

Now within the update method for the bullet pivot point, I rotate the pivot object in this direction:

transform.Rotate(direction.y * Time.deltaTime, -direction.x * Time.deltaTime, 0f);

This all is working great, until the ship and UFO start moving around the sphere. Eventually the calculated bullet direction goes from just slightly off, to mirrored once on the backside of the sphere... If I fly the ship back to the original starting point, the bullet direction comes back properly.

Not quite sure what the issue seems to be, and I've admittedly been looking at this far too long haha. Thanks in advance for any help on this!


texts: Use of SpriteFonts without installing on host machine

texts: I am working on a Windows game for my university project. In this project I am using a custom TrueType font which is not installed on any university computers. For submission my game is required to run in debug mode and a demonstration given. Therefore is there any possible way to read the font from within my project rather than installing the font on each computer that the project will be viewed on.


texts: No MODS button in Windows Minecraft when selecting Forge profile

texts:
I have installed a Minecraft launcher in Windows that supports Minecraft 1.14. I have installed Forge 1.14.4-forge-28.0.13. I have created the mods folder and placed a mod jar in it which is Xaeros_Minimap_1.17.4_Forge_1.14.4.

I have selected the Forge profile in the launcher. When running the launcher, I have to remove JVM option -XX:+CMSIncrementalMode in order to run it (also when running the regular profile). I have Java 11 installed.

But after launching, there is no MOD button in the menu. What could be the problem?


texts: irrlicht: drawing two textures with draw2dImage issue

texts:
Im just starting out with irrlicht (and c++) for 2d development and I followed the 2d tutorial, so I am able to draw a 2d texture on the screen (With draw2DImage) this seems to work fine.
So I made a seperate class where I draw a ship and also change it's position in the Update function, but here I run into a problem. The ship is drawn twice when I change it's position.
void Ship::Draw(irr::video::IVideoDriver * driver, irr::video::ITexture* texture) {
driver->draw2DImage((texture), this->position);
}

void Ship::Update(float gameTime) {
this->position.set(this->position.X += 1, this->position.X += 1);
}

The ship is drawn once on its original place (I guess 0,0) but it seems asif the ship is being copied and then that copy is.
in my main.cpp I have this:
ship1->Update(1);
ship1->Draw(driver, shipTexture);

(Also, the ship's texture is cut off after a while(as seen in the screenshot)).
And also, when I don't 'move' the ship (so I just change it's position once at startup (i.e. this->position.X = 100 this->position.Y = 100) then it behaves normally, so maybe there is something wrong with the way I set up everything?


texts: How to animate a bezier curve over a given duration

texts:
I have created a bezier curve by adding the following script to an empty game object in the inspector. This draws to complete curve at once when I run the code. How can I animate it over a given period of time, say 2 or 3 seconds?

public class BCurve : MonoBehaviour {

LineRenderer lineRenderer;
public Vector3 point0, point1, point2;
int numPoints = 50;
Vector3[] positions = new Vector3[50];

// Use this for initialization
void Start () {
    lineRenderer = gameObject.AddComponent<LineRenderer>();
    lineRenderer.material = new Material (Shader.Find ("Sprites/Default"));
    lineRenderer.startColor = lineRenderer.endColor = Color.white;
    lineRenderer.startWidth = lineRenderer.endWidth = 0.1f;
    lineRenderer.positionCount = numPoints;

    DrawQuadraticCurve ();

}

void DrawQuadraticCurve ()  {
    for (int i = 1; i < numPoints + 1; i++) {
        float t = i / (float)numPoints;
        positions [i - 1] = CalculateLinearBeziearPoint (t, point0, point1, point2);

     }
    lineRenderer.SetPositions(positions);
}

 Vector3 CalculateLinearBeziearPoint (float t, Vector3 p0, Vector3 p1,    Vector3 p2)   {

    float u = 1 - t;
    float tt = t * t;
    float uu = u * u;
    Vector3 p = uu * p0 + 2 * u * t * p1 + tt * p2;

    return p;
}


texts: Need help with gravity simulation in 2D game engine

texts:
I'm writing a 2D game engine using C++ and SDL2 and started implementing a rigidbody component similar to that of unity to my game objects. I have a method in the rigidbody class called AddForce which takes a 2D vector force as a parameter and calculates the velocity vector using \$F = MA\$.
I use this function to move the character left and right using the keyboard arrows. Now my question is, how do I manage the gravity with this and how do I calculate the resultant force of the gravity and the force applied when pressing either keyboard arrows.
Here is the rigidbody class:
#ifndef RIGIDBODY_H
#define RIGIDBODY_H

//Game engine libraries
#include "gameEngine/Game.h"
#include "gameEngine/GameObject.h"
#include "gameEngine/Component.h"
#include "gameEngine/components/Transform.h"

//GlM library
#include "glm/glm.hpp"

class RigidBody : public Component
{
private:
    Transform* m_transfrom;
private:
    float m_mass;
    float m_acceleration;
    glm::vec2 m_forceApplied;
    glm::vec2 m_velocity;
private:
    float m_deltaTime;

public:
    RigidBody(float mass)
    {
        m_name = "RigidBody";
        m_mass = mass;
        m_acceleration = 0;
        m_forceApplied = glm::vec2(0,0);
        m_velocity = glm::vec2(0,0);
     }
public:
     void AddForce(glm::vec2 force, float deltaTime)
     {
        float forceMagnitude;
        m_deltaTime = deltaTime;
        m_forceApplied = force;

        forceMagnitude = glm::length(force);
        m_acceleration = forceMagnitude / m_mass;
      }
 private:
     glm::vec2 CalculateVelocity()
     {
         float velocityMagnitude;
         static glm::vec2 newVelocity = glm::vec2(0,0);

         velocityMagnitude = m_acceleration * m_deltaTime;

         if(m_forceApplied.x != 0 || m_forceApplied.y != 0)
             newVelocity = glm::normalize(m_forceApplied);
         else
           newVelocity = glm::vec2(0,0);

         newVelocity = newVelocity * velocityMagnitude;

         return newVelocity;
      }

 public:
    void Initialize() override
    {
        m_transfrom = m_owner->GetComponent<Transform>("Transform");
    }
    void Update(Game instance, float deltaTime) override
    {
        m_velocity += CalculateVelocity();
        m_transfrom->position.x += m_velocity.x * deltaTime;
        m_transfrom->position.y += m_velocity.y * deltaTime;
    }
    void Render() override
    {

    }
 };

 #endif