texts: How do I wrap textures inside shader GLSL?

texts:
I'm trying out GLSL and one of the problems I'm facing is wrapping a random texture sampler in the shader. Searching for answers on the web first, this leads me to using these:

glTexParameter()
GL_TEXTURE_WRAP_S GL_REPEAT
GL_TEXTURE_WRAP_T GL_REPEAT

I'm not sure where to put this or how to use it. I'm using a custom engine for this shader and I would assume I could wrap the texture in the shader.

My main concern on this is my final output render having left and bottom artifacts. I got some previous advise it has to do with wrapping a random texture that is used for noise if that helps in my case.


texts: How can I hide the touch-screen joysticks in the main menu?

texts: I am a Unity beginner trying to make an app/game. How do I hide the touch-screen joysticks from showing on-screen in the main menu before the game/app actually starts?


texts: How do I get the 3d coordinates of my model Instance? [LibGDX]

texts:
I want to get the 3d coordinates (as a Vector3) from my model Instances.
with the following code I can only get the original coordinates, but in the render method, my model is rotating around the Y-axis (and moving at the same time) and I want to get its coordinates each frame.
I'm using a little class created by @Xoppa :

public static class GameObject extends ModelInstance {
    public Vector3 center = new Vector3();
    public Vector3 dimensions = new Vector3();
    public float radius;

    public BoundingBox bounds = new BoundingBox();

    public GameObject (Model model, String rootNode, boolean mergeTransform) {
        super(model, rootNode, mergeTransform);
        calculateBoundingBox(bounds);
        bounds.getCenter(center);
        bounds.getDimensions(dimensions);
        radius = dimensions.len() / 2f;
    }
}

and here's my code:

public void render(float delta) {
    super.render(delta);
    if (loading && manager.update()) {
        doneLoading();
    }

    Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);

    batch.begin();
    backgroundSprite.draw(batch);
    batch.end();

    for(GameObject instance : instances){
        instance.transform.rotate(new Vector3(0, 1, 0), 0.5f);
        float x = instance.bounds.getCenterX();
        float y = instance.bounds.getCenterY();
        float z = instance.bounds.getCenterZ();
        System.out.println(x+" "+y+" "+z);
        if(isVisible(cam, instance)){
            modelBatch.begin(cam);
            modelBatch.render(instance, environment);
            modelBatch.end();
        }
    }
}

Please help, there's no function "getPosition" or sth like that, it's all about Matrix4 and I have never had a math course about it. I'm stuck.


texts: Replacing a custom 3D model format with something more standard

texts:
This is long, so the short question is: What's the best/right/standard set of technologies for creating 3D models and incorporating them into a game such that the complexity for the artist is kept to a minimum while also keeping things relatively sane for the game authors?

The long story:

I am a developer for an open source space game called Pioneer. We currently have a custom 3D model format based around a Lua script that defines how the various objects in the model hang together.

The existing format has a lot of flexibility. It can load Wavefront objects or build its own from polygon primitives. It has a dynamic function that can emit tailored geometry each frame based on game state. It can also define various attributes and properties such as special collision surfaces, simple waypoints (use for automated docking with a space station), and so forth.

The feature set is more than enough for what we need right now, but its implementation leaves a lot to be desired. The actual script reader is almost 3000 lines of spaghetti. Model scripts are messy and require too much knowledge of the game engine. Matters are made worse by that fact that the original author is not readily available at the moment, so its left to others with little understanding of this system to fix things. We're also hearing some of our users say they can drive a modelling program just fine, but find the required Lua script to be completely incomprehensible. We don't want to turn these contributors away, so we need to find a way to help them.

(Some examples of model scripts, for the interested, can be found in our models repository).

As a result, I'm looking for a replacement. Ideally, I'd like to be able to point interested parties at something like Blender, tell them to draw a ship, define a few special properties and then export it, and that'd be that. On the code side, I'd very much like to be able to integrate a good third-party library that I can hand one of these files and just poke an object to get the necessary data back out. Anything that we can shift on to other, more competent projects is a win.

My question then, is what to use? I've done some searching and the best approach at this point appears to be to require artists to export their model in COLLADA format and then write a utilty based on FCollada to convert the export to some internal format. That's a little heavier than I think I want, but keeps things as easy as possible for the artist, which is the major requirement.

I'm very new to world of 3D modelling however, so I wouldn't be at all surprised to learn that there is a better way. Recommendations of standard/best practice for this sort of thing would be greatly appreciated.


texts: Unity / Rotate a point around an arbitrary axis and anchor

texts:
I'm trying to find out the point which is already rotated. To solve this I did a Rotation, save the position, set the previous position and return my position, like this:

Vector3 rotatePointAroundAxis(float angle ,Vector3 axis, Vector3 anchor)
{
Vector3 oldPosition = gameobject.transform.position;
gameobject.transform.RotateAround(gameobject.GetComponent<HingeJoint>().anchor, gameobject.GetComponent<HingeJoint>().axis, angle);

Vector3 newPosition = gameobject.transform.position;
gameobject.transform.position = oldPosition;
return newPosition;
}

I searched already. And I found very hard solutions.
http://inside.mines.edu/fs_home/gmurray/ArbitraryAxisRotation/
 - by the way i dont think I understand this, it seems like too much.

Is there any way to change that function to a "simple" one, so I don't need to rotate things forth and back to get the coordinates?

EDIT:

I believe tranform.RotateAround()  takes the position and rotation from the transform parameters and calculates the solution and changes the current position and rotation of the gameobject.

So the solution should take 5 parameters:

current position of the unrotated Object
current rotation of the unrotated Object
the point the Object should be able to pass
the rotation axis
the angle

and return 2 parameters:

the rotated objects new rotation
the rotated objects new position


texts: Math question: How to move/extrude a cube's face in Unity?

texts:
The short question is: What's the math to move the face of a cube? I.e. how to stretch (or shrink) a cube in the direction of one of its faces?
Here's a picture:

The camera shows a cube (left). When the user clicks and drags on one of the faces (yellow), the face (it's vertices) should follow the mouse and as a result expand (or shrink) the cube in the given direction (like the right cuboid in the picture above).
Please note that this should be done ingame, by moving the vertices, not by scaling the object.
Now, I already have the selected face and all the vertices of its four corners. Further, the distance how far it should be moved is also known.
The question is, what needs to be done with the vertices to pull the face out (or push it in)? Whats the math?
Your help is very much welcome. Thank you.


texts: How can I implement a real-time game loop in a text-based game?

texts:
I am trying to make a short text game with c++ to help me learn the language. I have made a version that basically displays texts, waits for an input, once the input is received it displays text, and so on. What I want to do now is make it so that it doesn't wait for the input. Real-time if you will. So certain values keep changing while the player is sitting, and if he sits for  too long that game changes in a major way.

My problem is that I can't figure out how to incorporate this in a my game loop. I have a while loop that has a input function, an update function, and a display function. Is this just something I have to do with a wait function?

(I am just using Visual C++ and nothing else).


texts: Any Open Source Games That Can Be Ported to Android?

texts: I'm looking for some other open source games out there that I can port (easily or not) to Android.  I know that it's possible to port Wolfenstein and Doom and was wondering if there are any others out there.  I was thinking of Civilization (I remember a linux port some time back) and a few others.  It can be in C/C++ or Java.  Thanks in advance.


texts:
EDIT: I've discovered the cause of the problem and it might make more sense if I continue in another question.

To start with unity has decided that lighting inside reflection probe bounding boxes is different :

This is fixed by disabling the probe but this isn't an acceptable solution.
I have no idea how to fix this.

Secondly:
Unity has decided to make my shadows flicker on and off (btw: kinda in sync to me pressing my mouse buttons)
Disabling the probes once again helped but this time did not solve the problem completely as the shadows would still flicker between resolutions.

Oh and I've been getting these bugs and no shadows at all sometimes:

rc.right == m_GfxWindow->GetWidth() && rc.bottom == m_GfxWindow->GetHeight()
GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly.

Please could someone help because I really don't understand why this is happening. Thanks...

Edit:
I was told that it would be necessary to detail what I've already done and some more information on the scene.

What I've tried:
Updating to the latest release of Unity (5.2.3f1)
Adjusting the near and far clipping planes
Turning things on off (GameObjects)
Changing the shadow settings (Shadow cascades, shadow distance)
Changing between Realtime and Baked Lighting and GI
Clearing the GI cache
Switching between deferred and forward rendering

If there's anything else anyone needs to know I will more than happily add it here because as I say I have no idea what you need to know to solve this.


texts: Turn Based AI Algorithm (Small Board, Two Steps)

texts:
This is my Game-Board:

-> The Red Balls are the AI-Controlled Actors.
-> The Blue Balls are the Player-Controlled Actors.
-> The Yellow Cells are the locations, from which the Red Balls can attack.
-> Each Red Ball can do 2 actions: move-move, move-attack, attack-attack.
-> At no time there can be 2 minions on one cell, but a minion can arrive on a cell another just left.

Its the AI's turn. Its planning the whole turn for all minions, each of them has the two moves.
The objective is to maximize the number of melee attacks, which can performed in a single turn (2 actions) on the player balls.

Problem I have in my current (brute-force) implementation:

Sometimes it is advisable for a minion to move, although it is already in a melee position, to make space for another minion, which can then move into melee range aswell.

Example:

In this situation its more effective for the front minion to move once, so another minion can move into melee range as well.

Do you know an effective algorithm for this job? Thank you for your time!


texts: How do I calculate an inverse bind-pose matrix for COLLADA?

texts:
I want to port a rigged mesh from a custom format to COLLADA. The bones I have define a position for the bone (local) and a matrix that transforms the child-bones' positions into the next-higher coordinate space. (The position of the root usually is {0, 0, 0}.)

How can I convert these to the inverse bind-pose matrices used for COLLADA?


texts: Achieve same effect as a FixedJoint2D but also match RigidBody2D forces

texts:
Trying to make an object that is affected by rigidbody physics in exactly the same way as the object it's linked to. So torque, velocity, and any resultant torque or velocity from a collision.

This image demonstrates what I mean:

I've tried using FixedJoint2D, my objects share velocity but do not share torque, applying torque doesn't do anything to either object, it seems locked. I tried using other joints, such as DistantJoint2D(doesn't match y value, only separation value), TargetJoint2D(immediately negates velocity), RelativeJoint2D(The closest to actually working, but glitches out when torque is applied, it acts on a centre of mass between the two connected objects and the objects sort of spin around each other, sometimes getting closer together or farther apart)

I also can't just apply the transform position and rotation to the second object, since these objects will be colliding with moving objects. The objects that they collide with slide into the squares and are pinched away when using this method.

So I need to know if there is a way to use the FixedJoint2D or RelativeJoint2D or another method or joint that I do not know of to achieve this same effect. Perhaps applying the collision forces happening to one object to the other but it needs to be immediate and I don't know how to apply the collision from one object to another.


texts: Unity3d generating a file in iOS and saving it on a linux machine

texts:
I've done a little research and don't know if the following is possible.

At the moment I have created a small application in Unity that generates an XML file. This file will be used to help set up my game. It's done in Unity due to it being cross platform with no need to re-write a single line of code. Eventually this will run on an iPad.

However, my game will be running on a linux computer and I need to pass over the XML file to the computer that will be running the final game (please don't ask why I'm doing that, it's something I need to do). So what I want to know is the following:

Can I generate my XML file on an iPad and have that XML file be saved, and transmitted to a linux machine, without the need to manually copy the file over. If so, how is this possible?


texts: Parabolic movement of a gameObject in Unity

texts:
Currently I'm working on a 3D game. In this game my player is a ball and it can jump from tile to tile. The movement of the ball is 45 degrees left or right when it jumps. I want to make it jump in a parabolic path. But I'm unable to do that.
I have used Mecanim, AngleAxis, and lerp as well. But the problem is when I use lerp and animation together, firstly the lerp works then the animation(Jump animation).
Basically the ball has a parent and mainly the parent lerps between the tiles and the ball itself has the animation clip attached to it.

Any suggestions or help is appreciated.


texts: Handling differing inventory items on use interactions

texts:
Hey there my fellow programmers. Looking for a little input into a potentially smelly code problem (I was about to post this on the Code Review SE, let me know if that's the more proper place).

After looking at a few of the answers here on setting up an rpg like inventory and using a component based system, I've come up with a format to creating items, here are a couple of examples.

Entity potion = new Entity("Potion", new Item(100,50), new Healing(75,0));
Entity elixer = new Entity("Elixer", new Item(50, 25), new TempStatIncrease(0,5,...));

Here are the classes involved.

Entity Class
IComponent[] components
string name

IComponent Interface
ComponentType componentType

Item Class : IComponent
int purchasePrice
int resaleValue

TempStatIncrease Class : IComponent
int strength;
int agility;
...

Healing Class : IComponent
int hpAmount;
int mpAmount;
Heal(Character character);

Now where I run into a bit of design trouble is how to handle interacting with these items. If I have "Potion" selected, and hit the use key in my inventory, it brings up the character list for me to select a character. When I select a character this is the code that would run:

Character Class
UseItem(Entity entity)
{
    foreach(IComponent component in entity.components)
    {
      switch(component.Type)
      {
         case Healing: { ((Healing)component).Heal(this); } break;
         case TempStatIncrease: { ((TempStatIncrease)component).Increase(this); } break;
         case ... //This could get ugly quick.
      }
    }
}

I feel like the above approach is prone to disaster. It's a switch for one, I have to modify this every time I want a character to be able to use a new component. Two, I have to do a not-so-nice cast to the concrete component. Add to the fact I have to create a new ComponentType enumeration for each new component, another piece of maintenance.

Any thoughts on how I might be able to re-factor my implementation to remove the potentially disastrous switch statement and that complex component casting?


texts: Best way to solve tile drawing in 2D side scroller?

texts: What i still can't figure out is which would be the more sane way / easier and faster way to draw the map on the screen.. I mean i will use many tiles for my maps in my side scroller.. But problem is should i make the maps in whole images like one .png file for each map (Example) or should i draw the tiles by code like a for loop in c++.. Which way is most recomended or where can i read about which way is the best.


texts: When specifying the material (ambient/diffuse/specular) for use in lighting calculations, what level of detail is the material specified at? Per vertex, mesh, bone?


texts: How can I move object to target then do something when reaching the target and then to move back to it's original position?

texts:
Inside Update :
if (finalLookWeight > 0.95f) // here you can play with a value between 0.95f -> 1.0f
                {
                    if (primaryTarget.interactableMode == InteractableItem.InteractableMode.Action
                        && IsAlreadyThrown == false)
                    {
                        // call your funtion to shoot something here
                        StartCoroutine(ThrowObject(objToThrow.transform, primaryTarget.transform, throwSpeed));
                        IsAlreadyThrown = true;
                    }
                }

I'm using a helper flag IsAlreadyThrown so the Coroutine will not start over and over again nonstop.
But I also want to be able from outside this script using in other script to change the flag IsAlreadyThrown back to false at some places/times in the game. How can I make that I can change the flag to false from other scripts ?
And inside the ThrowObject method I did :
IEnumerator ThrowObject(Transform objectToMove, Transform toPosition, float duration)
    {
        float counter = 0;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 currentPos = objectToMove.position;

            float time = Vector3.Distance(currentPos, toPosition.position) / (duration - counter) * Time.deltaTime;

            objectToMove.position = Vector3.MoveTowards(currentPos, toPosition.position, time);

            yield return null;
        }

        //StartCoroutine(ThrowBack(objectToMove, toPosition, duration));
    }

And :
IEnumerator ThrowBack(Transform objectToMove, Transform toPosition, float duration)
{
    float counter = 0;

    while (counter < duration)
    {
        counter += Time.deltaTime;
        Vector3 currentPos = objectToMove.position;

        float time = Vector3.Distance(currentPos, toPosition.position) / (duration - counter) * Time.deltaTime;

        objectToMove.position = Vector3.MoveTowards(toPosition.position, currentPos, time);

        yield return null;
    }
}

The first part is working fine the ThrowObject but then I tried to start the second Coroutine ThrowBack but it's just not doing anything.  The object is not moving and stay in the target position.  It's getting to the line :
objectToMove.position = Vector3.MoveTowards(toPosition.position, currentPos, time);

but the objectToMove just stay in position.
This is what I want to do more or less :
IEnumerator ThrowObject(Transform objectToMove, Transform toPosition, float duration)
    {
        float counter = 0;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            Vector3 currentPos = objectToMove.position;

            float time = Vector3.Distance(currentPos, toPosition.position) / (duration - counter) * Time.deltaTime;

            objectToMove.position = Vector3.MoveTowards(currentPos, toPosition.position, time);

            yield return null;
        }

        DoStuff(objectToMove, toPosition, duration);
    }

    void DoStuff(Transform objectToMove, Transform toPosition, float duration)
    {
        // do things when finish start the ThrowBack

        StartCoroutine(ThrowBack(objectToMove, toPosition, duration));
    }

At least this is the logic I want to do.


texts: How to get a Coordinates of a 3D Object in Android

texts: How is it possible to click on an area of a 3D Model (.obj-File) for example a cube, where you can get different Events of the six sides. For Example the orange area of the picture gives me a value of an Integer. The Cube can be rotated 360°.


texts:
I am at 1.2 stage (moving the player) at Unity course "Roll-a-ball" and have question:

I want to add feature that stops a player and sets his new position on 0, 0, 0.

I can reset the position, but I have really problem with stopping a player. The ball won't stop rolling.

My code is:

    using UnityEngine;
    using System.Collections;

    public class PlayerController : MonoBehaviour {

        private Rigidbody rb;
        public float speed = 1.0f;

        void Start()
        {
            rb = GetComponent<Rigidbody>();
        }

        void FixedUpdate()
        {
            float moveHorizontal = Input.GetAxis("Horizontal");
            float moveVertical = Input.GetAxis("Vertical");

            Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

            rb.AddForce(movement*speed);
            if (Input.GetKeyDown(KeyCode.Space))
            {
                rb.position = new Vector3(0,0.5f,0);
            }
            print(movement);
        }
    }

What I tried?

Adding new vector3 (0,0,0) in if section,
New vector3 that is opposite to movement,
.Stop after ascribing new position to (0,0,0), but it 'freezes' before (example: I click space when sphere is at board's edge, then it freezes there, when I click arrow it go to new position and start going).

So, how to do that? I have no clue right now, although problem seems
   be easy.

Here a image with code and Unity with opened Inspector on object.

EDIT

I've a another problem.

Changed code as below (as Byte56 suggested):

if (Input.GetKeyDown(KeyCode.Space))
{
    speed = 0;
    rb.velocity = Vector3.zero;
    rb.transform.position = new Vector3(0, 0.5f, 0);
    rb.constraints = RigidbodyConstraints.FreezeAll;
    speed = 1.0f;
}
if (moveHorizontal != 0 || moveVertical != 0)
{
    rb.constraints = RigidbodyConstraints.None;
}

It seems like clicing space not always freezes object. It always put it on right place, but sometimes doesn't freeze. No matter if I use code rb.constraints = RigidbodyConstraints.FreezeAll; or rb.Sleep(); - sometimes it works, sometimes not. I can't prove it, but it seems the smaller is delta of time between clicking space (smaller than 1 second) the chance that it won't freeze increases. It's not fault of space, I tried it with NumEnter.
Any idea? It seems really buggy.


texts: I need to be able to determine how long a key has been held down with high accuracy. For example if they key tapped really fast it could report a time that is less than the time for each update frame.


texts: How to decompose a 4x4 TRS transformation matrix with negative scale?

texts:
As the title says I need to decompose 4x4 TRS transformation matrices and extract the proper scale vectors and the proper rotation vectors (or rotation quaternions).
I know how to extract those information when the upper 3x3 matrix determinant is not negative. The problem is that those matrices can have that negative determinant and as far as I could understand, this negative determinant indicates a flip or mirrored transformation.
What do I have to do to extract the proper values for scale and rotation in those cases?


texts: What algorithm is mostly used to interpolate animations?

texts: Because DCC tools supports very many options, we resample the animation curve splines, but I think it still need to be interpolated. I think there's some de facto standard for this animation interpolation. Or no interpolation. Can I know what's the mostly used interpolation method?


texts: Is there a way to make the text look smoother and less pixelated? It bothers me.


texts: How to pass values in UE2Runtime to UnrealScript?

texts:
We have a game that launches via vbscript and calls UE2Runtime:

set demofile = filesys.GetFile("..neuro2\Inifiles\"&usrFoldername&"\LostWorld.ini")
'WShell.Run "..\System\UE2Runtime.exe LW1_basic.urt?Class=neuro2.Exp2Subject -log=" & usrName & "_training.log"

How do you grab the value in usrName that is passed to UE2Runtime to a console command in UnrealScript 2 when certain events are triggered in the game?

Many thanks in advance


texts: Does interfacing not work as well when it comes to games development?

texts:
I'm currently at the start of a project, and I'm following the wisdoms of my day-to-day career as a C# developer for large web applications.

Currently I have set up a bunch of interfaces. Notable of these are IActor, IHuman, ISelectable, IUIAction & IHealth.

I also have a Person class. Person implements IHuman (which implements IActor), ISelectable and IHealth and also inherits from MonoBehaviour.

ISelectable has a property of IEnumerable<IUIAction> Actions. Actions have a property of Action click. Im sure you can see where I am going with this...

The intended goal is that if a class inheriting from MonoBehaviour (person in this case) implements ISelectable and is attached to a GameObject that is clicked, a list of buttons representing ISelectable.Actions is displayed on the screen. If a class implements IHealth, a healthbar will be displayed on the screen etc etc...

Now, the problem I see is I'm going to end up with huge classes. The classes are going to need properties for their health, theyre going to need properties for their actions, theyre going to need properties for what the UI panels title should be when selected, and anything else that comes up as development progresses... My other thought is to remove the interfaces like IHealth from the class itself and have them be their own class, such that IHealth will only mean a class has a property that is of the class Health and Health has all the properties relating to an objects health levels... but this removes authority from the class as to what control it has over its health.

Whats the industry standard for this sort of thing, and how can I implement it effectively in my game?


texts:
I quite understand how projective texturing works. I implemented successfully a shader for that following nvidia doc.

The major problem I'm facing is that with that implementation the projector frustum is used only to determine the texture coordinate in projective space, but it doesn't clip anything outside the projective frustum volume.

In other words, if I have a projector pointing toward a object, the texture will be projected on it even if the object is outside its frustum.
In addition when projector is almost parallell to the projected object, the texture stretching is too evident and I would like to fade it out.

Now, I'm trying to understand how Unity handles their built-in projectors. I found this example.
Here's vertex and fragment relevant code:

v2f vert (float4 vertex : POSITION)
{
  v2f o;
  o.pos = mul (UNITY_MATRIX_MVP, vertex);
  o.uvShadow = mul (_Projector, vertex);
  o.uvFalloff = mul (_ProjectorClip, vertex);
  return o;
}

fixed4 frag (v2f i) : SV_Target
{
  fixed4 texS = tex2Dproj (_ShadowTex, UNITY_PROJ_COORD(i.uvShadow));
  texS.rgb *= _Color.rgb;
  texS.a = 1.0-texS.a;

  fixed4 texF = tex2Dproj (_FalloffTex, UNITY_PROJ_COORD(i.uvFalloff));
  fixed4 res = texS * texF.a;
  return res;
}

I think that _Projector matrix is a classical matrix to transform vertices coordinates into projector space. (In fact the fragment just use the transformed coordinates to sample the projected texture).

What I'm really missing is how Unity construct _ProjectionClip matrix. The transformed vertex coordinates are used to sample the falloff texture (that I think it is what I really need).

Does anyone know how the _ProjectionClip is constructed? Or how to achieve a similar effect?

Note:
I did something similar for calculating spotlights falloff, but there I used a single matrix multiplication in the vertex shader to transform vertices into lightspace, and the squared distance in the fragment shader to calculate texture coords for a lookup into the attenuation texture.


texts: Shadow flickering with first-person near clipping plane

texts:
After adding a first-personal controller asset, world shadows flicker like crazy. I don't understand the cause, and everything I've tried based on googling has failed to help.

https://i.imgur.com/Mx5MCKB.gifv

I've tried:

Increasing the near clipping plane of the camera. The first-person asset I have defaults to 0.01. Changing it to 0.1 or higher seems to solve the issue, except that breaks the first-person view.
Toying with bias value on the directional light
Changing Render Mode from Auto to Important on the directional light
Changing the Shadow Projection quality to Stable Fit

The authors of the asset have not been able to help, though it doesn't seem to be specifically related to their product, just the clipping planes required.

I'm using Unity 2019.1.2f1 Personal.


texts: Where can I find code examples of different variations of Perlin noise?

texts:
I have seen the PCG wiki, and it is a great resource. But a lot of the articles are very brief and it is hard to find good links on specific things.

I have been searching for ways to transform my Perlin noise height maps to make ridges, rivers, and other terrain features. I also can't find any articles on how to divide up the map into different areas for calculating texture coordinates or other values specific to the game. I have only been able to find websites detailing their software that can generate the different things, but no code or explanations. Are there any good sources of code examples/explanations on how to do the above mentioned with Perlin noise?

PS. This should probably be a community wiki. I don't know how to make it as one though.


texts:
Environment:

Windows 7 x64
Visual Studo 2012
DirextX11
HLSL Shader Model 5
Ogre 1.9

Okay, so I'm trying to sample a texture in my pixel shader but I'm coming across some strange problems.  Here's the pixel shader:

struct PS_INPUT {
    float4 pos : SV_POSITION;
    float2 uv  : TEXCOORD0;
};

Texture2D tex0;
SamplerState s0;

float4 pixel_shader(PS_INPUT input) : SV_TARGET {
    float3 texSample = tex0.Sample(s0, input.uv);

    float4 color = float4(1,1,1,1);

    color.xyz = texSample;

    return color;
}

If you want / need it here's the ogre .material definition:

material simpleMat
{
    technique
    {
        pass simpleMat
        {
            vertex_program_ref vertex_shader {}
            fragment_program_ref pixel_shader {}
        }

        texture_unit 0
        {
            texture diffuse.png 2d
            tex_address_mode wrap
        }
    }
}

This produces mostly black on my object, but I get 2 random white pixels.  But here's the strangest part.  When I debug the pixel shader in visual studio texSample nearly always equals zero.  So I decided to try something crazy, I debugged the program, got the value of input.uv and then modified the shader to use these values explicitly.  When I do this texSample actually contains the correct color value.  So yeah...  any help is much appreciated!

Rojuinex

EDIT

Here is a snapshot that shows the issue in detail:

http://www.pasteall.org/pic/show.php?id=74835

EDIT 8/4/2014

Upon further investigation I have discovered that the further the object is from the camera, the darker the texture becomes.  If the camera is right up against the object, the texture has the right color values, but as it moves away the sampler returns darker and darker values until they are black.


texts: how do i make the JS/jquery tic tac toe squares only clickable once?

texts:
As i have it now my script makes the 3x3 grid clickable, and I dont know exactly how to turn on the click once it has been clicked. This is using jQuery and a simple if else statement to switch between turns.

    $(document).ready(function(){
  var turn = 0;
    $("#cell11, #cell12, #cell21,  #cell22, #cell13, #cell23, #cell31, #cell32, #cell33, ")
            .click(
            function(){
                var cell = $(this);
                if(turn===0){
                    turn = 1;
                cell.css("background","url(images/o.png)");
                }
                else{
                    turn = 0;
                    cell.css("background","url(images/x.png)");
                }
            })
});


texts: Implementing a time scale in game with fixed physics update

texts:
I'm currently putting together my game loop based on the "Fix Your Timestep" article at gafferongames.com. This is going fine, but I'm also trying to implement a 'time scale', i.e. a way to control the game speed.

Currently, the delta time is added to an accumulator, and then a loop iterates the physics as many times as there are multiples of the fixed time step in the accumulator.

Now, if I want to add a time scale, I should multiply the delta time by some factor, 0.5 for half speed or something, yes?

Here are my questions:

Should I still use the real fixed time step (prior to multiplication) to determine how often the physics is iterated, but perform the actual calculations with the increased or decreased time step? Or should I use the new time step for both, but surely this would just result in the same behaviour but with higher resolution calculations?

Wait, wait, wait. I have to affect the accumulator too, right? Then it would increase by a smaller frame time, but it would do the right amount of iterations with smaller dTs, over the right amount of time (the real delta time). That'd do it, right?

Given that the purpose of the fixed time step is to perform stable physics calculations, how can I combine these two concepts without jeopardising that stability?

Is it simply that LARGE time steps cause instability? Can I therefore slow down as much as I like? Or is it the variations in time step that causes instability?

Thanks


texts: Maintaining velocity of free fall body using Box2D in libGDX

texts:
I want to maintain the speed of a free-falling Box2D body using LibGDX. I'd like the vertical velocity increase with the level. I've applied a linear impulse and velocity actually increases like this:

fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);

I think this is a bad approach, because the speed has increased only a little and I applied as much as -800 units of impulse.

Below is my render function of game play screen class:

    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

//      camera.update();
//      batch.setProjectionMatrix(camera.combined);
        batch.begin();

        backgroundSprite.draw(batch);
        grassSprite.draw(batch);

//      bucketSprite.draw(batch);

        Iterator<Body> bodies = world.getBodies();

        while(bodies.hasNext()){

            Body body = bodies.next();

            if(body.getUserData() != null){

                String spriteName = (String) body.getUserData();

                Sprite sprite = (Sprite) userDataMap.get(spriteName);

                if(spriteName.equals("bucket"))
                    sprite.setPosition(body.getPosition().x + 345, body.getPosition().y + 230);
                else
                    sprite.setPosition(body.getPosition().x + 375, body.getPosition().y + 225);

                sprite.draw(batch);

            }
        }

        batch.end();

        fruitBody.applyLinearImpulse(0, -800, fruitBody.getLocalCenter().x, fruitBody.getLocalCenter().y, true);
//      debugRenderer.render(world, camera.combined);
        world.step(1/60f, 8, 3);
//      world.clearForces();
    }

My world is:

world = new World(new Vector2(0, -10), true);

Orthographic camera:

camera = new OrthographicCamera(800, 480);

My fruitBody fixture def is:

bodyDef.type = BodyType.DynamicBody;
        bodyDef.position.set(0, 100);

        // shape
        CircleShape ballShape = new CircleShape();
        ballShape.setRadius(15f);

        //fixture
        fixtureDef.friction = .1f;
        fixtureDef.restitution = .7f;
        fixtureDef.shape = ballShape;
        fixtureDef.density = .2f;

        fruitBody = world.createBody(bodyDef);
//      fruitBody.setUserData(fruitSprite);
        fruitBody.setUserData("fruit");
        fruitBody.createFixture(fixtureDef);

I just want to increase the fruit's speed (free falling body) at each level by a given value.


texts:
I dont know why i need to call super.paintComponent() and super.repaint() to make the player's movements update, if i just put paintComponent the game seems like to always be stopped. However I think that my mistake is the render() method, if a remove it, it doesn't make any difference, so it is useless, I've been looking for the error but I still can not see it. I would appreciate some help

Here is the paint method of the drawing class

public void paint(Graphics g) {
    super.paintComponent(g);

    setFocusable(true);
    requestFocusInWindow();
    setBackground(Color.BLACK);
    player.drawPlayer(g, getPosX(), getPosY());
    enemy.drawEnemy(g);
    //I know this should not be here
    super.repaint();
}

Pricipal GameLoop and render method

public void run() {
    long lastLoop = System.nanoTime();
    final int TARGET_FPS = 60;
    final long OPTIM_TIME = 1000000000 / TARGET_FPS;
    long lastFPSTime = 0;
    int fps = 0;
    double delta = 0;

    while (running) {
        long now = System.nanoTime();
        lastLoop = now;
        delta += (now - lastLoop) / ((double) TIEMPO_OPTIMO);

        lastFPSTime += (now - lastLoop);
        fps++;

        if (lastFPSTime >= 1000000000) {
            System.out.println("[FPS : " + fps + " ]");
            lastFPSTime = 0;
            fps = 0;
        }

        while (delta >= 1) {
            render();
            delta--;
        }

        try {
            Thread.sleep((System.nanoTime() - lastLoop + OPTIM_TIME) / 1000000);
        } catch (InterruptedException ex) {
            Logger.getLogger(mainGameLoop.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

public void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(2);
        return;
    }
    Graphics g = bs.getDrawGraphics();
    drawing.paint(g);
    g.dispose();
    bs.show();
}

And as last and least probable, I thought that maybe there is something that is not adding correctly to my window

A normal window class

Drawing drawing = new Drawing();

public Window(String title,int width, int hight, mainGameLoop mainGame){
    JFrame frame = new JFrame(title);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width, hight);
    frame.setLocationRelativeTo(null);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.add(mainGame);
    frame.add(drawing);

    mainGame.start();
    mainGame.run();


texts: How to avoid game starting before start button is clicked?

texts:
I've made a game with a Title Screen (Canvas), and a Start Button attached to the Title Screen. Points, GameOver, Restart, and even the Start Button sort of works, but it's possible to play the game before the user presses start.

Is there a way to make the GameObjects only appear after the button is clicked? I've tried to move and change the "public void StartGame()", but I can't get it right.

This is my first game ever, so hope the code provided is relevant.

Enemy.cs

 void Start()
{
        enemyRb = GetComponent<Rigidbody>();
        gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
        player = GameObject.Find("Player");
}

GameManager.cs

 public void StartGame()
{
    powerup.transform.rotation);
    score = 0;
    UpdateScore(0);
    isGameActive = true;
    titleScreen.gameObject.SetActive(false);
}

void Update()
{
    enemyCount = FindObjectsOfType<Enemy>().Length;

    if (enemyCount == 0)
    {
        roundNumber++;
        SpawnEnemyIntruders(roundNumber);
        Instantiate(powerup, GenerateSpawnPosition(), powerup.transform.rotation);
    }
}

void SpawnEnemyIntruders(int enemiesToSpawn)

{
  for (int i = 0; i < enemiesToSpawn; i++)
  {
      int enemyIndex = Random.Range(0, enemies.Length);
      Instantiate(enemies[enemyIndex], GenerateSpawnPosition(), enemies[enemyIndex].gameObject.transform.rotation);
  }
}
public void GameOver()
{
    restartButton.gameObject.SetActive(true);
    gameOverText.gameObject.SetActive(true);
    isGameActive = false;
}

PlayerController.cs

    void Start()
{
    playerRb = GetComponent<Rigidbody>();
    playerAudio = GetComponent<AudioSource>();
}

StartButton.cs

    void Start()
{
    button = GetComponent<Button>();
    gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    button.onClick.AddListener(StartThis);
}


texts: How do I properly check if a particular OpenGL version is available?

texts:
I can't find any information on glCreateContextAttribsARB returning errors if a version is unsuported by the driver. So how do i check if it is? I don't want the program to hard crash because glCreateContextAttribsARB failed and i had no chance to check why it did.

Here's my code, i try to keep it minimalistic, the OpenGLVersion uses the glGetIntegerv to get the major and minor didgits and creates a number out of it. It checks if the version is 'least 3.3, though i've no idea if this actually does anything unless i set up glCreateContextAttribsARB with the wrong numbers.

So when does OpenGL "get a version", so that the glGetIntegerv returns a valid information? Is it something built in or does it return something valid only after i set up the context? How do i check if the OpenGL version i want to use is supported?

void CreateOpenGLContext(HWND hWnd){

    //Set the pixel format

    PIXELFORMATDESCRIPTOR pfd =
    {
        sizeof(PIXELFORMATDESCRIPTOR),
        1,
        PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
        PFD_TYPE_RGBA,
        32,
        0, 0, 0, 0, 0, 0,
        0,
        0,
        0,
        0, 0, 0, 0,
        24,
        8,
        0,
        PFD_MAIN_PLANE,
        0,
        0, 0, 0
    };

    hDC = GetDC( hWnd );
    GLuint PixelFormat = ChoosePixelFormat( hDC, &pfd );
    SetPixelFormat( hDC, PixelFormat, &pfd );

    //Create an OpenGL context to get access to the WGL extensions

    hRC = wglCreateContext( hDC );
    wglMakeCurrent( hDC, hRC );

    //Load functions

    if(glload::LoadFunctions() == glload::LS_LOAD_FAILED){
        MessageBox( NULL, TEXT("Failed to load OpenGL extensions."), TEXT("Error"), MB_OK | MB_ICONEXCLAMATION );
        PostQuitMessage(0);
    }

    //Load WGL extensions

    if(glload::LoadWinFunctions(hDC) == glload::LS_LOAD_FAILED){
        MessageBox( NULL, TEXT("Failed to load WGL extensions."), TEXT("Error"), MB_OK | MB_ICONEXCLAMATION );
        PostQuitMessage(0);
    }

    //Use WGL extensions to create an OpenGL 3.3 context

    const int contextAttributes[] =
    {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
        0
    };

    HGLRC hRC3 = wglCreateContextAttribsARB( hDC, hRC, contextAttributes);

    wglMakeCurrent( hDC, hRC3 );
    wglDeleteContext( hRC );
    hRC = hRC3;

    //Check if the system supports OpenGL version 3.3

    if(OpenGLVersion() < 33){
        MessageBox( NULL, TEXT("Your system doesn't support OpenGL version 3.3"), TEXT("Error"), MB_OK | MB_ICONEXCLAMATION );
        PostQuitMessage(0);
    }
}


texts: What is the easiest way to Implement a 3rd Person Camera in C++/DirectX9

texts:
I'm pretty new to C++ and DirectX9 and I want to Implement a Third Person Camera. After some reading about Quaternion-based Cameras I decided to try Implementing it. But it really blow my mind, so I ask here what is the easiest way to Implement a TP-Camera?

Here are the things the Camera should do:

Follow coordinates stored in a 3DVector (x, y, z)
Rotate around the Object (Smooth)
Maybe some type of 'spring' = Slowly moving back to the normal Pos behind the Object after Rotating

Apologise for my bad english: I'm german and still in school!

Thanks in Advance!

EDIT:

After some trying I've got it.

The biggest problem I considered was the right extracting of the "direction" Vector from the World-Matrix.

During my research I've found mostly something like this:

D3DXVECTOR3 direction;
direction.x = worldMatrix->_13;
direction.y = worldMatrix->_23;
direction.z = worldMatrix->_33;
D3DXVec3Normalize(&direction, &direction);

That does NOT work for me! Instead I did this:

D3DXVECTOR3 direction;
direction.x = worldMatrix->_13;
// Consider the .y after the .z!
direction.z = worldMatrix->_23;
direction.y = worldMatrix->_33;
D3DXVec3Normalize(&direction, &direction);

For scaling:

// The tenfold of the average distance
D3DXVec3Scale(&direction, &direction, 10.0f);

Setting the Positions:

cameraPos = targetPos - direction;
// For a top-view
cameraPos.y = targetPos.y + 5;

For Rotations you should create a temporary world-Matrix (from the position of the target) and rotate it how you want and extract the direction.

The Smoothing of the Rotation really depends on YOUR game!

This sort of 3rd Person Camera is really easy to make and it does it's job!

Really GREAT thanks to "jheriko" who gave me the right answer!


texts: How can I prevent rigid bodies from moving through each other using Unity's built-in physics?

texts:
I'm trying to create a game where objects can be dragged, but I'm having trouble with the physics. With rigid bodies that have similar masses, they sometimes push through each other when dragged and cause unwanted movements. Here is a demo.

I'd like to do this using only Unity 3D's built-in physics.

In the demo, you can use the mouse to click and drag objects. The cylinders all have box colliders and masses of 10000. They also have various constraints depending on their orientation (none can rotate, and all are constrained in x or y). The sphere has a mass of 1, a sphere collider and a z constraint.

The sphere and cylinders interact well. However dragging the cylinders across one another causes intersection. I do not want this!

The cylinders have interpolate set to 'Interpolate' and collision detection set to 'Continuous'. I have thrown the 'DontGoThroughThings' script onto all the cylinders, but it doesn't seem to do anything. As for setting the velocity of the rigidbodies, I have used both of these following lines with basically the same result:

rb.AddForce(speed * diff * Time.deltaTime - rb.velocity, ForceMode.VelocityChange);
//rb.velocity = speed * diff * Time.deltaTime;

Without writing my own collision detection code, I'm out of ideas. Is there a simple setting or something I've missed?

With the context explained, here's a more precise question: "How can I get the cylinders in my demo to not move through each other?"


texts: Integration of Game Loop + Physic Engine : when to delete objects?

texts:
How to manage code around physic engine, when a game object should be deleted?

I will use a tiny game as an example:-

1st iteration of development

I have a very simple game with 1 character (Jumper) and many platforms.

The game loop is like this :-

system_jumper.update();     //game-logic
system_platform.update();   //game-logic
system_physic.update();     //This is the only place where physic object will be actually added/removed.

system_physic.update() executes everything as batch (for performance reason).

If game-logic wants to creates / remove some physic objects,
such commands will be cached - postponed to be executed in the system_physic.update().

It is very good so far.

2nd iteration of development

I want to remove a platform in a certain time-step.

I added a new line just before the system_physic.update(), as followed:-

system_jumper.update();
system_platform.update();
if(timestep==10)system_platform.removeId( platformId );  //#
system_physic.update();     //the rigid body is deleted here

The #-line wishes to do 2 things.

I. remove physic object of the platform        (the command is
buffered)
II. remove logical game object of the platform

At that #-line, I can't delete the platform (both physic & logic part) immediately,
... because when the deletion command is executed in system_physic.update(),
... the physic callback for "end-collision" for the platform will be called.

When the callback occurs, the physic engine accesses the corresponding game object (platform's logical part in this case).

Therefore, at system_physic.update(), the platform must not be deleted yet.

My poor solution

As a result, I hack it a bit, like this:-

system_jumper.update();
system_platform.update();
system_platform.removeId___BUFFER_DELETE_PHYSIC( platformId); //[I] Hacking logic
system_physic.update();          //the rigid body is deleted here
system_platform.removeId___DELETE_LOGIC_NOW( platformId);  //[II] Logic delete

It works, but it is very ugly i.e. low maintainability.

Question

Is it common that game logic code ugly like this?
Is the buffer command (for physics) a bad idea in the first place?
How to professionally solve this maintainability problem?

(Low maintainability because codes about deletion scatter around, I & II)

The real problem is more complex that this, but the root is the same as  question.
(I usually encapsulate the hack inside some systems.)

P.S. This is an example of callback, provided just in case:-
The Jumper has a counter of platform that it step on, to determine whether the jumper can jump.
It is implemented by physic callback (object start collide +=1, object end collide  -=1).


texts: Assets bundles have higher size than uncompressed sprites

texts:
I've created a script that generates assets bundles by compressing sprites using LZ4 compression. I need this in order to generate smaller files that I'll download from a server at runtime but after taking a look at those bundles. I've found out that they actually have a higher size than the uncompressed sprites.
For example, I've generated a bundle from three sprites that have a size of 201KB together, but if I take a look at its generated bundle, its size is 300KB. This is only one example, there are other bundles that are 6MB but their original files are only 500KB and that doesn't make any sense to me. Can someone point me in the right direction?


texts: Collider2D and Rigidbody2D, how do they work?

texts:
I have been learning JavaScript and Unity for a week now. I learned how to make Cube as a Ground and another Cube as a player and I used this code to make the Player Cube move forward and backward and jumping

var walkspeed: float = 5.0;
var jumpheight: float = 250.0;
var grounded = false;

function Update() {

    rigidbody.freezeRotation = true;

    if (Input.GetKey("a"))
       transform.Translate(Vector3(-1, 0, 0) * Time.deltaTime * walkspeed);
    if (Input.GetKey("d"))
       transform.Translate(Vector3(1, 0, 0) * Time.deltaTime * walkspeed);

    if (Input.GetButton("Jump")) {
        Jump();
    }
}

function OnCollisionEnter(hit: Collision) {
    grounded = true;
}

function Jump() {
    if (grounded == true) {
        rigidbody.AddForce(Vector3.up * jumpheight);
        grounded = false;
    }
}

I also learned how to make a character hit box. how to make a sprite and animation. pretty much the basic stuff.

Couple of days ago I created simple ground in Photoshop and a simple character and imported them to Unity3D. Whenever I use my code above the character keeps falling from the scene. Like the character has nothing to stand on. After thinking about it it make sense because I really didn't make anything to make the player character understand that he should stand on something so I started reading about this issue and I realized that there is something called Collider2D and Rigidbody2D.

Now I'm really stuck here I just don't know what to do. I applied the rigibody2d to my character picture and the Collider2D to the ground picture but whenever I play the project the gravity makes my character falls down.

This is my question:

How can I make the rigibody2d object realize that it shouldn't fall if there is a Collider2D object under it? So when I jump it's going to jump and the gravity going to bring it back to the ground.


texts: Google Play Game Services Logcat warning

texts:
I'm getting the following warning in my LogCat output.  I have implemented Google Play Games Leaderboards which, after some research, it appears this warning is related to....

I would point out that my app works fine, it's already published and scores have been submitted to the leaderboard, however, I would like to get rid of this warning if I can but I'm honestly unsure why I have it in the first place.

I've read quite a few questions relating to this warning, however in those questions, there were also actual problems with the Play Games Services not working.

My Activity class is extending BaseGameActivity.  Like so:

public class MainActivity extends BaseGameActivity implements
ConnectionCallbacks, OnConnectionFailedListener, AdListener{

    //And I will then use getGameHelper() to carry out the various calls
    //For example

    getGameHelper().beginUserInitiatedSignIn();

    getGameHelper().reconnectClient();

}

The official tutorial, now seems to suggest extending Activity and not BaseGameActivity and creating a GoogleApiClient object (unless I'm looking in the wrong place).  As I don't have a GoogleApiClient object, I can't access setViewForPopups.

Is this something that I need to worry about and if so, how do I get rid of it?  It's not causing any issues, however, I'm worried by the 'may not work properly in future versions of the API' part.

Extremely confused, so any help appreicated.


texts: I was wondering if Node.js was suitable for making games and apart from threads and engines, a big problem is can I port my game to Xbox or PS3/PS4?


texts: What is a good approach for making a relationship between the HUD and Environment?

texts:
What is an elegant / common way to build a relationship between the game scene / environment / world and the HUD that usually sits on top of it? I have thought about this for a while, and though there are ways to accomplish this that are easy to implement, they always seem to expose too much unrelated information between the two, or end up being too coupled. An example of this that I have used in the past would be to simply pass reference from the HUD to the Environment and vice-versa (which is obviously not a good apporach for many reasons, especially when aiming for low coupling).

What I want to end up with is a clean, uncoupled way to do things like:

From the HUD; reference and manipulate objects within the environment, change the state of the Environment itself.
From the environment; update the HUD to reflect the current state of the environment.

Maybe passing reference between the two is the way to go about this, but I feel like there's some pattern that I am missing for this type of task. Any insights into past experience and implementations concerning this type of problem would be very helpful.


texts: How to implement a birds eye view of 2D Grid Map using Android

texts:
I'm a true beginner with using the android platform and I'm having difficulties on implementing a 2D grid system for a tower defense type game. Where I can place towers on a specific tile and enemies will be able to traverse through tiles etc.

What I would like is a practical explanation of how I could tackle this. A step by step guide for dummies.

This is what I believe are the necessary steps to take, I think I might be wrong but I hope someone could help me out.

 Calculate the Width and Height of the view I'm working with.
 Based on that, determine the number of tiles required and their dimensions, (Still not sure how I would do this)
Create each tile as a Rectangle object and draw these rectangle on a canvas

I would really be grateful if someone could steer me in the right direction on how to implement a 2D Grid Map using android. I hope the answer to this questions helps the TRUE beginners out there like me.

I have looked at the following links below yet I still feel that I don't trully understand what's going on.

For XNA: 2D Grid based game - how should I draw grid lines?

How to Create a Grid for a 2D Game?

Also a quick note: All my previous game development has been in Java, mostly using Java SE and Swing. I also have good understanding of the game development process, it is only android thats confusing me :S

Update: I was actually able to implement, I have decided to post a link to a wiki-page of mine which I have started working on sometime back but not been able to progress further with it.

A simple solution to this can be found here: https://bitbucket.org/iadan/pathfinding/wiki/Home


texts: How to handle a different kinds of weapon in a single component and system in entity system?

texts:
A weapon can be used as melee or range weapon, it can be thrown, toss, fired, shoot, cast (a projectile) or use to slash, bash, stab . How do I apply these to entity-system? my first approach is to create an enum class of WeaponType, a melee or range.

public enum WeaponType {
    MELEE,
    RANGE
}

public interface Weapon {
    void use();
}

Then I've create a weapon component and add weapon type data, to determine its type. For melee a weapon, it needs to have a method that handles different kind of "attack motion" like slash, bash, stab. For range weapon, it needs to have a container, factory and a method that handles different kinds of "projectile motion" like shoot, fire, throw, toss etc.. Now the problem is how could I create a method for different kinds of projectile motion, remember I am specifically using Ashley ECS framework

public class WeaponComponent implements Component {
    public Weapon weapon;
    public WeaponType type;
    // if weapon type is melee, use the below data
    public Container container // holds the created projectile
    public Factory factory // creates a different kinds of projectile object
}

// or create seperately???

public class MeleeWeaponComponent implements Component {
    ... different kinds of method also like slash, bash, stab
}

public class RangeWeaponComponent implements Component {
    ... Factory and Container
    ... different kinds of projectile motion?
}

In this idea, I can use abstract or interface but I think abstraction or is not recommended.

[Combined data suggestion] by @Ryanwhite and me

Blue line is area of effect angle covered
Green line is distance covered
Red point is the target point

public class WeaponComponent implements Component {
    public Ray ray // to handle collisions
    public float aoe; // 0.5 for melee, more than 0.5 for other weapon
    public float aoeAngleCovered;
    public float aoeAngle
    public Ammo[] // 0 for melee, 1 or more for other weapon
}


texts: How do I efficiently code both the client and server at the same time?

texts:
I'm coding my game using a client-server model. When playing on singleplayer, the game starts a local server, and interacts with it just like a remote server (multiplayer). I have done this to avoid coding separate singleplayer and multiplayer code.

I have just started coding and have encountered a major problem. Currently I'm developing the game in Eclipse, having all the game classes organized into packages. Then, in my server code, I just use all the classes in the client packages.

The problem is, these client classes have variables that are specific to rendering, which obviously wouldn't be performed on a server.

Should I create modified versions of the client classes to use in the server? Or should I just modify the client classes with a boolean, to indicate if its the client/server using it. Are there any other options I have? I just had a thought about maybe using the server class as the core class, then extending it with rendering stuff?


texts: This for array colllision function doesn't work with anything but first object in array

texts:
For some reason, this simple simple loop is totally broken.
(characterSheet is my character Class, it's just a movieClip with some extra functionality)
(hitBox, is basically a square movieclip)

Anyway: every time hitBox make contact with a characterSheet in a different order than they were created: Nothing happens.  The program only seems to be listening to collisions that are made with o2[0].  As soon as another hitBox is created, it pushes the last one out of o2[0] and the last one becomes totally useless.
What's super weird is that I can hit characterSheets in any order I like....

    public function collisions(o1:Array, o2:Array)
    {
        if((o1.lenght>=0)&&(o2.length>=0)){
            for (var i = 0; i < o1.length; i++)
            {
                var ob1 = o1[i];
                for (var f = 0; f < o1.length; f++)
                {
                    var ob2 = o2[f];

                    if (ob1 is characterSheet)
                    {   if (ob2.hitTestObject(ob1))
                            {
                                var right:Boolean = true;
                                if (ob1.x < hitBox(ob2).origin.x)
                                    right = false;
                                characterSheet(ob1).specialDamage(hitBox(ob2).damageType, hitBox(ob2).damage, right);
                                }}}}}}

Also it might be somewhat helpful to see the function for creating a new hitBox

    public function SpawnHitBox(targeted, following, atype, xoff, yoff, ... args)
    {
        var newHitBox = new hitBox(targeted, following, atype, xoff, yoff, args);
        badCollisionObjects.push(newHitBox);
        arraydictionary[newHitBox] = badCollisionObjects;
        addChild(newHitBox);

    }


texts: Centering Image inside ImGui window causes bug

texts:
I've tried drawing RenderTexture directly to the ImGui window and I've stumbled upon a bug. Everything is drawn correctly until I center ImGui Image inside the ImGui window.
Centered Image:

Not centered Image:

As you can see when Image is centered in the ImGui window some lines aren't showing up (they are drawn and I'm not talking about first vertical line, last horizontal etc.) but when Image is slightly off-centered RenderTexture is drawn properly. Is it a bug or am I doing something wrong?
Example source code:
#include "imgui.h"
#include "imgui-SFML.h"

#include <SFML/Graphics.hpp>

const sf::Time TIME_PER_FRAME = sf::seconds(1.0f / 60.0f);
bool isTextureLoaded = false;

void render_grid(sf::RenderTexture &renderTexture)
{
    sf::Vertex line[2];
    for (int i = 0; i <= renderTexture.getSize().y; i += 32)
    {
        line[0] = sf::Vector2f(0, i);
        line[1] = sf::Vector2f(renderTexture.getSize().x, i);
        renderTexture.draw(line, 2, sf::Lines);
    }

    for (int i = 0; i <= renderTexture.getSize().x; i += 32)
    {
        line[0] = sf::Vector2f(i, 0);
        line[1] = sf::Vector2f(i, renderTexture.getSize().y);
        renderTexture.draw(line, 2, sf::Lines);
    }
}

void process_imgui(sf::RenderWindow &window, sf::RenderTexture &renderTexture, sf::Sprite &sprite)
{
    //ImGui::SetNextWindowPos(ImVec2{ 251, 20 });
    ImGui::SetNextWindowSize(ImVec2{ static_cast<float>(window.getSize().x - 251.0f), static_cast<float>(window.getSize().y - 20.0f) });
    ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2{ 0, 0 });
    ImGui::Begin("Tileset", nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysHorizontalScrollbar);

    renderTexture.clear();
    renderTexture.draw(sprite);
    render_grid(renderTexture);

    //float x = (ImGui::GetWindowSize().x - static_cast<float>(renderTexture.getSize().x)) * 0.5f; //doesn't draw grid correctly
    float x = (ImGui::GetWindowSize().x - static_cast<float>(renderTexture.getSize().x)) * 0.499f; //draws grid correctly
    ImVec2 imagePosition(x, 20.0f);
    ImGui::SetCursorPos(imagePosition);
    ImGui::Image(renderTexture, ImVec2(static_cast<float>(renderTexture.getSize().x), static_cast<float>(renderTexture.getSize().y)));

    static bool saveToFile = true;
    if (saveToFile)
    {
        sf::Image image(renderTexture.getTexture().copyToImage());
        image.saveToFile("correct.png");
        saveToFile = false;
    }

    ImGui::End();
    ImGui::PopStyleVar();
}

int main(void)
{
    sf::RenderTexture renderTexture;
    sf::Texture texture;
    sf::Sprite sprite;

    sf::RenderWindow window(sf::VideoMode(1600, 900), "Test");
    window.setFramerateLimit(60);
    window.resetGLStates();

    texture.loadFromFile("test1.png");
    renderTexture.create(texture.getSize().x, texture.getSize().y);
    sprite.setTexture(texture);

    renderTexture.draw(sprite);
    render_grid(renderTexture);

    ImGui::SFML::Init(window);

    sf::Clock clock;
    sf::Time timeSinceLastUpdate = sf::Time::Zero;

    while (window.isOpen())
    {
        sf::Time elapsedTime = clock.restart();
        timeSinceLastUpdate += elapsedTime;

        while (timeSinceLastUpdate > TIME_PER_FRAME)
        {
            timeSinceLastUpdate -= TIME_PER_FRAME;

            sf::Event event;
            while (window.pollEvent(event))
            {
                ImGui::SFML::ProcessEvent(event);

                if (event.type == sf::Event::Closed)
                    window.close();
            }
        }

        ImGui::SFML::Update(window, elapsedTime);
        process_imgui(window, renderTexture, sprite);

        window.clear();
        ImGui::SFML::Render(window);
        window.display();
    }

    ImGui::SFML::Shutdown();
    return 0;
}

Example texture:


texts:
I am making a basic 2D platformer. I want to get the relative position of one rectangle to another.

This is how I do it right now:

const float offset = 5;
if (x1 <= x2 && x1 + w1 >= x2)
            {
                if (Math.Abs(y1 + h1 - y2) <= offset)
                    return CollisionType.Top;
                else if (Math.Abs(y1 - h2 - y2) <= offset)
                    return CollisionType.Bottom;
                else if ((y1 <= y2 && y1 + h1 >= y2) || (y1 >= y2 && y1 <= y2 + h2))
                    return CollisionType.Left;
            }
            if (x2 <= x1 && x2 + w2 >= x1)
            {
                if (Math.Abs(y1 + h1 - y2) <= offset)
                    return CollisionType.Top;
                else if (Math.Abs(y1 - h2 - y2) <= offset)
                    return CollisionType.Bottom;
                else if ((y1 <= y2 && y1 + h1 >= y2) || (y1 >= y2 && y1 <= y2 + h2))
                    return CollisionType.Right;
            }

            return CollisionType.NoCollision;

Here how this function works (or at least how I suppose it to work):

Using this function, I often have collision bugs, but I cannot understand a global rule of when it happens. I don't think that a bunch of if blocks would solve the problem.

I need a collision detection function that receives two arguments of type Entity (The class can contain any fields or functions, but it must have an X, a Y, a Width and a Height) The function needs to return the relative position of the first rectangle to the second.

What improvements would you suggest to my current function or is there a better system for collision detection in 2D games where one needs to get a relative position instead of a simple true false?


texts:
I am creating a game using OpenGl in c++. Whenever I create a new model while the game is running, such as fire a bullet, there is a huge lag spike. The function that creates the model is below.
    std::string jsonString;
    jsonString = file->load(type);
    json jf = json::parse(jsonString); //Might be causing the lag

    indicesSizeTexture = jf["textureIndices"].size();
    verticesSizeTexture = jf["textureVertices"].size();
    indicesSizeCollision = jf["collisionIndices"].size();
    verticesSizeCollision = jf["collisionVertices"].size();
    verticesTexture = new float[verticesSizeTexture * 8];
    verticesCollision = new float[verticesSizeCollision * 8];
    verticesCollisionUpdated = new float[verticesSizeCollision * 8];

    indicesTexture = new int[indicesSizeTexture];
    indicesCollision = new int[indicesSizeCollision];

    for (int i = 0; i < verticesSizeTexture; i++) {  //responsible for just the texture vertices
        verticesTexture[i] = jf["textureVertices"][i];
    }
    for (int i = 0; i < indicesSizeTexture; i++) { // responsible for just the texture indices
        indicesTexture[i] = jf["textureIndices"][i];
    }
    for (int i = 0; i < verticesSizeCollision; i++) {  //responsible for just the collision vertices
        verticesCollision[i] = jf["collisionVertices"][i];
        verticesCollisionUpdated[i] = verticesCollision[i];
    }
    for (int i = 0; i < indicesSizeCollision; i++) { // responsible for just the collision indices
        indicesCollision[i] = jf["collisionIndices"][i];
    }

    //binds id
    glGenBuffers(1, &VBO);
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &EBO);
    glGenTextures(1, &texture);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, verticesSizeTexture * 8 * sizeof(float), verticesTexture, GL_STATIC_DRAW);
    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    //texture
    glBindTexture(GL_TEXTURE_2D, texture);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    stbi_set_flip_vertically_on_load(true);
    unsigned char* data = stbi_load(texturePathString.c_str(), &width, &height, &nrChannels, 0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
    stbi_image_free(data);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

I stripped out a lot of parts that I am almost certain aren't causing the lag. There is a lot of stuff going on, but it is mostly simple mathematical operations. The only parts that I think could be causing the lag is the json section used for loading the model data. The model data is stored in a variable from file as a string. I need the json section for the data storage though. What could be causing the lag? should I find a different data storage type? What if I created a bullet offscreen on startup, then copied it whenever I needed it? The specific json library I am using is https://github.com/nlohmann/json


texts: How can I create a musical sheet using sprites?(Ocarina of time )

texts:
I am looking to make a musical sheet similar to the image below:

I want to:

use sprites prefabs
have each sprite correspond to a different line
Move down notes are more are being played
have tail end notes disappear or go outside of text view (like when you type past a search bar)

I am unsure if there is a UI asset in Unity that can perform what I just mentioned. I was thinking could just instantiate the prefabs in the right positions, shift them down, then delete the tail end prefabs as more are being played. Outside of that, I'm lost.


texts:
I'm trying to find the best design pattern for my AI code using an ECS.

Right now the entities that act as CPU-controlled have components like:

WeaponComponent
ChargeComponent
MovementComponent
AIControlledComponent

...

I have an AIControlSystem that goes over the entities that have the AIControlledComponent and during each frame switches the mental state of the entity based on some rules like "can I see the player?", "can I move somewhere safe?", etc...

Based on the mental state, this systems adds a set of actions to a queue.

Then the queue is being consumed and evaluated. An action like "Attack" is actually calling a method of the system that checks whether the entity has a WeaponComponent attached and fires, or if there's a ChargeComponent it charges at the player. This way, those methods tend to grow as the kind of enemies and actions grow and the code starts to become a mess as there are way too many checks and paths to follow.

I thought I could refactor the code splitting it up based on the kind of enemy (aka an enemy that has a Weapon won't be able to Charge and vice versa) but then I'd have to have a base AIControlSystem and inherit from that and specialize it based on the components attached to the entities. This would result in pretty much one new system per enemy kind and it doesn't really look like a good solution.

I thought about diverging from the pure ECS pattern of keeping components as data containers only and actually implement those methods in the components themselves so that I can have a base AIControlledComponent with the virtual methods that interpret the queue of actions and inherit a new component from that one for each enemy type. It looks a bit better for code organization but I'm not sure that making this kind of exception is a good idea.

Is there any other way to keep the code under control and at the same time have the flexibility needed?


texts: Are these non-standard applications of rendering practical in games?

texts:
I've recently got into 3D and I came up with a few different "tricky" rendering techniques. Unfortunately I don't have the time to work on this myself, but I'd like to know if these are known methods and if they can be used in practice.

Hybrid rendering

Now I know that ray-tracing is still not fast enough for real-time rendering, at least on home computers. I also know that hybrid rendering (a combination of rasterization and ray-tracing) is a well known theory. However I had the following idea: one could separate a scene into "important" and "not important" objects. First you render the "not important" objects using traditional rasterization. In this pass you also render the "important" objects using a special shader that simply marks these parts on the image using a special color, or some stencil/depth buffer trickery. Then in the second pass you read back the results of the first pass and start ray tracing, but only from the pixels that were marked by the "important" object's shader. This would allow you to only ray-trace exactly what you need to. Could this be fast enough for real-time effects?

Rendered physics

I'm specifically talking about bullet physics - intersection of a very small object (point/bullet) that travels across a straight line with other, relatively slow-moving, fairly constant objects. More specifically: hit detection. My idea is that you could render the scene from the point of view of the gun (or the bullet). Every object in the scene would draw a different color. You only need to render a 1x1 pixel window - the center of the screen (again, from the gun's point of view). Then you simply check that central pixel and the color tells you what you hit. This is pixel-perfect hit detection based on the graphical representation of objects, which is not common in games. Afaik traditional OpenGL "picking" is a similar method.

This could be extended in a few ways:

For larger (non-bullet) objects you render a larger portion of the screen.
If you put a special-colored plane in the middle of the scene (exactly where the bullet will be after the current frame) you get a method that works as the traditional slow-moving iterative physics test as well.
You could simulate objects that the bullet can pass through (with decreased velocity) using alpha blending or some similar trick.

So are these techniques in use anywhere, and/or are they practical at all?


texts: Android Action_Move when moving between specific screen areas

texts:
OK so I know how to iterate through the different pointers that are currently touching the screen so I know what the coordinates are of these pointers using the following:

Code snippet

case MotionEvent.ACTION_MOVE:{

    //Count through all the pointers currently touching the screen
    for(int index=0; index<event.getPointerCount(); index++) {

     //Is finger on the left button? If so, then go (or continue going) left
    if (event.getY(index) > renderer.leftButton("top") && event.getX(index)<renderer.leftButton("right")){
                renderer.setSpritewState('l', true);
                renderer.setSpriteState('r', false);}

 //Or is finger on the right button? If so, then go (or continue going) right
            else if (event.getY(index)>renderer.rightButton("top") && event.getX(index)>renderer.rightButton("left") && event.getX(index)<renderer.rightButton("right")){
                renderer.setSpriteState('l', false);
                renderer.setSpriteState('r', true);}
            }
            break;

}

However, this is constantly triggering one of the two conditions I guess as it's picking up minute movement of the finger/s. And, more importantly, if there is a finger on each 'button' - the sprite goes a bit crazy as each condition fights with the other and constantly flags the sprite to move left and then right etc.

What I'm really after is this something like this:

So, if a finger moves within a specified area, nothing happens as it's counter-productive.  But if a finger moves from one area to another, then the action is triggered.

I'm guessing the code for this would need to save the old position of each of the fingers to compare to the new positions, but I'm not really sure how to go about this.  Help would be appreciated.  Thanks.


texts: How do I get the DirectX project templates to appear in Visual Studio?

texts: I have DirectX11 on Windows 7, and I also have VS13 Express for Desktop. In some tutorials I have seen that there's an option on VS13 for new project on DirectX, but doesn't appear in my VS13. Is it because I have the for Desktop version instead of the for Windows one? Or do I need to install some DirectX developmentkit first? Thanks.


texts: Collection of Simple Children's Game Mechanics

texts:
Context:

I've tried Googling / searching on Amazon for books on this, but I end up get all types of resources on "How to Gamify XYZ" rather than the mechanics of simple games.

I'm trying to build a collection of "simple game mecahnics" that often shows up in Children's games. For example:

color in the picture
fill in pieces of a puzzle
memory/matching game

Question:

Is there some gigantic list of these "mechanics of simple games" ? Somewhere?

I don't need actual implementation (I can do that on my own).

I just need english descriptions of what the mechanics are.

Thanks!


texts:
Say I have the general engine working and the only thing missing is a story line.

Let's take the Pokemon games as an example:
How would I implement surfing if I don't want to check wether the next tile is a water tile on every step I take? (I assume this would be horrible performance wise)
The guards will let me pass once I have delivered some juice to them. How would this be done?

The second one should I should be able to implement with a state machine. Am I correct in understanding that a state machine is an enum(java) with my different states?

The other thing I am a little bit confused about is Events. For example how would I implement that if I step on a certain tile my character dies - again without checking this for EVERY tile I step on. I believe the tile would need to call some sort of Event that then kills my character. How should I write my "EventHandler"?


texts: Adding Openai's GPT3 to a Unity project?

texts:
I have a text-based project and it has a slot open for Openai's GPT3 model. My project has a terminal module where the user receives emails, I want to go a step further and allow the user to respond to such emails and get some unique response.
Here is a rundown of how I want it to work: User receives "email", they respond to it, GPT3 steps in and feeds a response into a new "email".
So how would I approach this? I think this could be pretty interesting as GPT3 hasn't been implemented in any games yet. I am aware that some beefy hardware may be required but my development computer is quite beefy enough.
P.S. Sorry if my title isn't specific enough, closest thing I could think of for this situation.


texts: How to make an object which position is not on the world origin rotate around the world orgin in threejs?

texts:
I've loaded an object and set its position on vector(5,2,-5) by threejs. And I wanted it to rotate around the origin point in the world coodinate system. I found a method in class Object3D called 'rotateOnWorldAxis', so I had a try on it but it didn't work, it still rotate on it own space. I want to know why it didn't work and how to make this right.

The code is like this:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
//resize event
window.addEventListener("resize",function(){
  var width = window.innerWidth;
  var height = window.innerHeight;
  renderer.setSize(width,height);
  camera.aspect = width / height;
  camera.updateProjectionMatrix();
});

camera.position.set(0,0,15);

var ambientLight = new THREE.AmbientLight(0xffffff,0.8);
scene.add(ambientLight);

var mesh;
var fgxloader = new THREE.FBXLoader().
load("asset/source/1520514930250.FBX",function(object){
  object.position.set(5,2,-5);
  scene.add(object);
  mesh = object;
},function(xhr){
  console.log("object "+(xhr.loaded/xhr.total*100)+"% loaded");
},function(error){
  alert(error);
});

var rotateSpeed = 0.1;
var update = function(){
  if(mesh===undefined)
    return;
  mesh.rotateOnWorldAxis(new THREE.Vector3(0,0,0),rotateSpeed);
  //mesh.rotateOnAxis(new THREE.Vector3(0,1,0),rotateSpeed);
  //mesh.rotateY(rotateSpeed);
  //mesh.rotation.y += rotateSpeed
};

var render = function(){
  renderer.render(scene,camera);
};

var GameLoop = function(){
  requestAnimationFrame(GameLoop);
  update();
  render();
};

GameLoop();


texts:
Can someone tell me how to implement collision in Pygame?
For example I have a sprite called A and another one called B.
How do I detect if they collide in Pygame?


texts: LibGDX: How to make something like vector rotation sensor with accelerometer and compass values?

texts:
So I've tried the vector rotation sensor using the Android API and it works perfectly to do what I want, but LibGDX does not support this sensor. I've been searching and it seems like I can do the same thing as vector rotation sensor using the accelerometer and compass values returned by LibGDX API:

Gdx.input.getAccelerometerX();
Gdx.input.getAccelerometerY();
Gdx.input.getAccelerometerZ();

Gdx.input.getAzimuth();
Gdx.input.getPitch();
Gdx.input.getRoll();

But I couldn't find out how to do this.


texts: How to scale image at runtime in GameMaker?

texts:
I use this code to create a new enemy and preset some values:

It runs in the step event of the player object.

var inst_inst = instance_create_layer(newX, newY, "Instances_Enemies", obj_Asteroid01);
inst_inst.image_index.image_xscale = 0.1;
inst_inst.speed = 4;

The speed is set correctly but the code scales the image of the player sprite and not the sprite of obj_Asteroid01

Edit after getting the answer

My fault was to trust the autocomplete and the fact, that there were no compile errors.

This is something you need to get used to :)


texts: Ive been searching for an easy way to group multiple sprites of a spritesheet into a single entity. Im using tiled editor as written at the title. Some objects might be larger than the tile size and i need a way to let my game know that in order to manipulate these objects. I dont want to create new tilesets with different sizes for all objects. Is this possible in this app and if not do you know another that can handle this?


texts: How do I correct the turning effects on my car in order for it to turn properly?

texts:
In my game, I'm currently working on a Physics-based car driving game in Unity from scratch. My problem is that whenever I press the input controls used for turning, instead of turning, my car does barrel rolls in the air. I'm using a document written about Car Physics by Marco Monster to aid some of my calculations in this post. I've looked at my code and suspect that the problem lies within this segment of my code. Please provide any feedback as it would be greatly appreciated.
//This section relates to low-speed cornering, not really useful for drifting
            //This will determine the circle radius related to turning, in effect, calculating how much we turn
            R = L / Mathf.Sin(userRight);

            //Here, we calculate the vehicle's angular velocity in radians per second
            //Omega (fancy w) represents angular velocity
            // v represents velocity
            rb.angularVelocity = rb.velocity / R;

        //This section covers high-speed turning
            //This relates to the car
                //sideSlipAngle = Vector3.Angle(carTransform.forward, rb.velocity);
                sideSlipAngle = Mathf.Atan(rb.velocity.z / rb.velocity.x);

        //This relates to the wheels
        for(int i = 0; i < 4; i++)
        {
            //alpha represents the slip angle for each wheel
            alpha = Vector3.Angle(wheels[i].forward, rb.velocity);

            //this equation is an approxiamtion of values below the peak shown in the graph
            lateralForce = new Vector3(0f, 0f, corneringStiffness * alpha);

            //These values are supposed to represent the magnitudes of these velocities
            longVelocity = Mathf.Cos(alpha) * rb.velocity;
            latVelocity = Mathf.Sin(alpha) * rb.velocity;

            /*
                Remember that these forces are supposed to be acting upon the wheels themselves,
                so add rigidbodies accordingly
             */

            //The lateral velocity causes the cornering force to counteract it
                //This relates to only the front wheels
                frontSlipAngle = Mathf.Atan((latVelocity.magnitude + (rb.angularVelocity.magnitude * b)) / longVelocity.magnitude) - (userRight * Mathf.Sign(longVelocity.magnitude));
                for (i = 0; i < 2; i++)
                {
                    //Calculates the lateral force of the wheels
                    latFrontForce = lateralForce.normalized * (frontWeight.magnitude / 2f);
                    latFrontForce += latFrontForce;

                    corneringForce = latRearForce + Mathf.Cos(userRight) * latFrontForce;
                    lateralForce += latFrontForce;

                    frontTorque = Mathf.Cos(userRight) * latFrontForce * b;
                    //rb_wheels[i].AddForce(lateralForce);
                }

                centripedalForce = corneringForce;
                steeringRadius = centripedalForce.magnitude / (rb.mass * Mathf.Pow(rb.velocity.magnitude, 2f));

            //This relates to only the rear wheels
            rearSlipAngle = Mathf.Atan((latVelocity.magnitude - (rb.angularVelocity.magnitude * c)) / longVelocity.magnitude);
            for (i = 2; i < 4; i++)
            {
                //Calculates the lateral force of the wheels
                latRearForce = lateralForce.normalized * (backWeight.magnitude / 2f);

                latRearForce += latRearForce;
                lateralForce += latRearForce;

                rearTorque = -latRearForce * c;
                //rb_wheels[i].AddForce(lateralForce);
            }

        }

        totalTorque = frontTorque + rearTorque;
        rb.AddTorque(totalTorque);
```


texts:
I'm extending the terrain quad with resources from various tutorials and have the following code:

public class WorldTerrain extends TerrainQuad {

    public static final String NAME = "terrain";
    public static final int PATCH_SIZE = 9;
    public static final int TOTAL_SIZE = 33;
    private static Vector3f spawnLocation = new Vector3f(13, 3, 16);
    private Material mat_terrain;

    private void loadText(AssetManager assetManager) {
        /**
         * 1. Create terrain material and load four textures into it.
         */
        mat_terrain = new Material(assetManager,
                "Common/MatDefs/Terrain/Terrain.j3md");

        /**
         * 1.1) Add ALPHA map (for red-blue-green coded splat textures)
         */
        mat_terrain.setTexture("Alpha", assetManager.loadTexture(
                "Textures/Terrain/splat/alphamap.png"));

        /**
         * 1.2) Add GRASS texture into the red layer (Tex1).
         */
        Texture grass = assetManager.loadTexture(
                "Textures/Terrain/splat/grass.jpg");
        grass.setWrap(WrapMode.Repeat);
        mat_terrain.setTexture("Tex1", grass);
        mat_terrain.setFloat("Tex1Scale", 64f);

        /**
         * 1.3) Add DIRT texture into the green layer (Tex2)
         */
        Texture dirt = assetManager.loadTexture(
                "Textures/GrassRocky.png");
        dirt.setWrap(WrapMode.Repeat);
        mat_terrain.setTexture("Tex2", dirt);
        mat_terrain.setFloat("Tex2Scale", 32f);

        /**
         * 1.4) Add ROAD texture into the blue layer (Tex3)
         */
        Texture rock = assetManager.loadTexture(
                "Textures/Terrain/splat/road.jpg");
        rock.setWrap(WrapMode.Repeat);
        mat_terrain.setTexture("Tex3", rock);
        mat_terrain.setFloat("Tex3Scale", 128f);
    }

    private static float[] generateHeightMap(AssetManager assetManager) {
        AbstractHeightMap heightmap = null;
        try {
            heightmap = new HillHeightMap(1024, 100, 2, 10, 1);
        } catch (Exception ex) {
            Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
        }
        return heightmap.getHeightMap();
    }

    public static Vector3f getSpawnLocation() {
        return spawnLocation;
    }

    public WorldTerrain(Interface app) {
        super(NAME, PATCH_SIZE, TOTAL_SIZE, generateHeightMap(app.getAssetManager()));
        loadText(app.getAssetManager());
        setMaterial(mat_terrain);

        setModelBound(new BoundingBox());
        setLocalTranslation(32f, 0f, 32f);

        List<Camera> cameras = new ArrayList<Camera>();
        cameras.add(app.getCamera());

        RigidBodyControl landscape = new RigidBodyControl(0.0f);
        addControl(landscape);

and the interface:

public class Interface extends SimpleApplication {

  private TerrainQuad terrain;
  Material mat_terrain;

  public static void main(String[] args) {
    Interface app = new Interface();
    app.start();
  }

  @Override
  public void simpleInitApp() {
    flyCam.setMoveSpeed(50);

    terrain = new WorldTerrain(this);
    rootNode.attachChild(terrain);
  }

This gives the following result:

as you can see large parts of the terrain are not rendering (ignore the weird mountains those are only tests). If I move the camera around these holes move around suggesting it's a rendering problem in the terrain. Anybody who knows how to fix?


texts: SetCursor: Cursor does not contain a definition for "SetCursor' or why can't I re-assign the cursor in Unity 20194.7f?

texts:
Here is the code I used on Cursor script, attached to a chest object.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cursor : MonoBehaviour
{

    public Texture2D cursorArrow;
    // Start is called before the first frame update
    void Start()
    {
        //Cursor.visible = false;

        Cursor.SetCursor(cursorArrow, Vector2.zero, CursorMode.ForceSoftware);
    }

}

For some reason, I can no longer reset cursor properties and I don't know why. Please help?


texts: Is there any way that I can make rounded corners on a rectangle rendered in XNA through primitives (line-strips)? I want to make my UI a bit more fancy than it is already, and I would like the code to be flexible, without too many textures involved.


texts: Keeping track of onscreen objects in opengl es on Android

texts:
In a small game Im working on I was able to implement ray picking with an opensource 3d engine called min3d but I cant figure how to keep track of what object is onscreen. I will some times have upwards of 120 objects to render within my scene and the raypicking is off occasionally. What id like to do is keep track of how many screen objects are within the camera and being rendered onscreen and set a boolean value based on that to add or remove objects from my arraylist I iterate through when the screen touch is registered and the ray picking method goes off.

So how can I check for which objects are onscreen and offscreen in opengl es on android.


texts: What does the green arrow in Unitys MonoDevelop mean? It comes up while I am debugging my code:


texts: How can I build a graphical map for my MUD engine?

texts:
I am working on a text-based game totally from scratch and one thing I am not sure how to do is the map system.

In my mud engine totally writen in Javascript (that will be executed in a Node.js environment), I use that kind of data to design an area and the links between rooms.

/**
 *       [003]-[004]
 *         |     |
 * [001]-[002] [007]
 *         |     |
 *       [005]-[006]
 **/
var map = {
    "001" : {
        "Id" : "001",
        "Name" : "Room 001",
        "Directions" : {
            "N" : "",
            "S" : "",
            "E" : "002",
            "W" : ""
        }
    },
    "002" : {
        "Id" : "002",
        "Name" : "Room 002",
        "Directions" : {
            "N" : "003",
            "S" : "005",
            "E" : "",
            "W" : "001"
        }
    },
    "003" : {
        "Id" : "003",
        "Name" : "Room 003",
        "Directions" : {
            "N" : "",
            "S" : "002",
            "E" : "004",
            "W" : ""
        }
    },
    "004" : {
        "Id" : "004",
        "Name" : "Room 004",
        "Directions" : {
            "N" : "",
            "S" : "007",
            "E" : "",
            "W" : "003"
        }
    },
    "005" : {
        "Id" : "005",
        "Name" : "Room 005",
        "Directions" : {
            "N" : "002",
            "S" : "",
            "E" : "006",
            "W" : ""
        }
    },
    "006" : {
        "Id" : "006",
        "Name" : "Room 006",
        "Directions" : {
            "N" : "007",
            "S" : "",
            "E" : "",
            "W" : "005"
        }
    },
    "007" : {
        "Id" : "007",
        "Name" : "Room 007",
        "Directions" : {
            "N" : "004",
            "S" : "006",
            "E" : "",
            "W" : ""
        }
    }
};

On the MUD game I am actually playing, the mud command display something like this:

I would like to know in pseudo-code the way to do this in the most efficient way.

Please note that it has a maximum character length for each lines and that the map is centered around You (@).

Thank you for your help!


texts:
The most advanced games I've made are a 8-ball pool game made with the physics engine Box2dFlashAS3 and a platform game with levels.

When I did platform games, I've always wished to know how to make an engine, so that I could re-use it. When I see games that have slopes, curved slopes, perfect gravity and real-life physics, I've always wished I knew how to code the engine.

Please suggest techniques and articles for whatever relevant knowledge-base is necessary.


texts: Should I be using Lua for game logic on mobile devices?

texts:
As above really,

I'm writing an android based game in my spare time (android because it's free and I've no real aspirations to do anything commercial).

The game logic comes from a very typical component based model whereby entities exist and have components attached to them and messages are sent to and fro in order to make things happen.

Obviously the layer for actually performing that is thin, and if I were to write an iPhone version of this app, I'd have to re-write the renderer and core driver (of this component based system) in Objective C.

The entities are just flat files determining the names of the components to be added, and the components themselves are simple, single-purpose objects containing the logic for the entity.

Now, if I write all the logic for those components in Java, then I'd have to re-write them on Objective C if I decided to do an iPhone port. As the bulk of the application logic is contained within these components, they would, in an ideal world, be written in some platform-agnostic language/script/DSL which could then just be loaded into the app on whatever platform.

I've been led to believe however that this is not an ideal world though, and that Lua performance etc on mobile devices still isn't up to scratch, that the overhead is too much and that I'd run into troubles later if I went down that route?

Is this actually the case? Obviously this is just a hypothetical question, I'm happy writing them all in Java as it's simple and easy get things off the ground, but say I actually enjoy making this game (unlikely, given how much I'm currently disliking having to deal with all those different mobile devices) and I wanted to make a commercially viable game - would I use Lua or would I just take the hit when it came to porting and just re-write all the code?