texts: Without using a pre-built physics engine, how can I implement 3D collision detection from scratch?

texts:
I want to tackle some basic 3D collision detection and was wondering how engines handle this and give you a pretty interface and make it so easy... I want to do it all myself, however.

2D collision detection is extremely simple and can be done multiple ways that even beginner programmers could think up:

When the pixels touch;
when a rectangle range is exceeded;
when a pixel object is detected near another one in a pixel-based rendering engine.

But 3D is different with one dimension, but complex in many more so... what are the general, basic understanding/examples on how 3D collision detection can be implemented?

Think two shaded, OpenGL cubes that are moved next to each other with a simple OpenGL rendering context and keyboard events.


texts: How do I write to z-buffer in a transparent Unity 5 shader without a shadow caster?

texts:
I've seen plenty of examples of "priming the depth" buffer with this pass:

Pass
{
    Tags{ "LightMode" = "Always" }
    ColorMask 0
}

But it does nothing in Unity 5. How do I write to the depth buffer (_CameraDepthTexture) in Unity 5 without using a shadowcasting pass?


texts: Farseer: Friend/Foe Collision - cannot push foes but friends

texts:
we are using Farseer in our project and I try to find a setup to achieve the following quite complicated collision behavior:

Friendly Units can push each other aside. However, the push should be a "soft-push", so that multiple units can squeeze through narrow gaps.
Enemy Units should not be pushed. Ever. Moving units colliding with enemies should stop dead.
Additionally, I have some other type of collider, lets call them "Wall" ;). Neither friends nor foes should ever be able to stand inside a wall.

Whether two objects are considered "enemies" can change dynamically during the game. The state is always symmetric (If Bob is an enemy of Alan, then Alan is always an enemy of Bob) but we have more than two factions (up to 16).

(Basically, its a similar collision behavior like Starcraft, except that friendly units can temporarily squeeze through navmesh gaps.. much like in Age of Empire..)

Actually, I got a quite elaborated solution so far. It has some problems, but kind of gets most of my wishlist done.. Well, most of the time. Here is what I did..

Lets first start with the setup without any walls (because that's what is working better ;):

I have 2 bodies for each unit. One dynamic the other kinematic.
the dynamic body has two equal fixtures. One sensor (to soft-push friends), the other a normal fixture (this is what I apply forces from outside game code).
The kinematic body has one normal fixture. (This body is to dead-stop on enemies)
I hooked a BeforeCollision callback to the normal fixture of the dynamic sensor. This filters out all collisions except with the kinematic body of enemies. This way, the dynamic body can not push enemies.
Another BeforeCollision filter on the kinematic body just excludes collisions with the sensor fixture of our own dynamic body.
Now, after every world update, I run through all the dynamic bodies:

I will copy the new position into the kinematic body.
For each touching contact of the sensor with another dynamic body, I will manually calculate a separating force and apply these to both dynamic bodies.

Everything clear so far? To summarize: Dynamic fixture moved by game code, stops dead colliding with kinematic body of enemies. Sensor register friends and I calculate push-forces by hand. Kinematic body is synched every frame to the dynamic body.

Now the problem: Walls.

I need to enforce that no Body ever ends up inside a wall. More precise, the center point of any body must not be inside any Wall - shape (the circle can and should overlap with the wall, only the center point is interesting).

I tried several ideas to achieve this but running out of steam here. The currently best solution I could come up with:
- The dynamic body gets yet another circle fixture that is extremely small, like 0.001 meter.
- This one has a CCD on and a collision group that only allows collision with walls (which are in their own category)
- Walls are all fixtures of a static body.

This approach works as long as no "teleporting" of units is involved. Lets say Alan is being teleported on a spot overlapping with Bob. Now, Alan's kinematic body will push Bob's dynamic body and vice versa. Everything is fine. But if Bob was standing right next to a wall, Farseer will still move Bob slightly into the wall, since the resolver need to resolve the unmovable kinematic body of Alan and the unmovable wall.

Yet another post-update loop through all bodies that scans all units whether they are inside walls and manually resolve their positions is way beyond our performance limits.

I briefly thought about some solution involving two separate Farseer worlds, but my head starts to spin trying to figure out which body position need to be copied where and when... ^^

I haven't looked into joints yet, but my gut feeling is that they don't really help here. Except with a third body? Do I really need 3 bodies per unit? :(

Any ideas?


texts: Alternatives to remove Unity splash screen after developing a game with the free version?

texts:
I developed a simple game using the free version of Unity. I want to understand how much it would cost me to remove the Unity Splash Screen to know if it's worth it.

Right now Unity professional edition costs $75 per month, does this mean I have to pay every month while the game is on the app store or can I pay just for the month I have to release the game so I remove the Unity Splash Screen and that's all (provided I don't need to update the game later)?


texts: Scrolling and Parallax scrolling in 2D game

texts:
I'm developing a 2D side-scrolling game.I have a scrollable bitmap for background with size 2400x480.How can i scroll this bitmap?I have searched for algorithms but i can't find any solution.

I know that i can do it with following code:

for(int i=0;i<100;i++)
draw(bitmap,2400*i,480);

So it will scroll bitmap for 240000 pixels.

But i don't want to draw images which stays out of screen(with size 800x480).

How can i render scrolling tile?How can i give velocity to it?(For parallax scrolling after normal scrolling)


texts:
I have drawn several vector objets and characters ( in Adobe Illustrator ) for my game on Android. They are all scalable at any size without any quality losses ( of course it's vector ^^ ).

I have tried to simulate my gameboard directly on Illustrator just before setting my assests on libdgx to implement them in my game.

I set all the objects at the good size, so that they fit perfectly on my XHDPI device I am running my test on.

As you can see it works great ( for me at least ^^ ), the PNG quality is good for me, as expected !

So I have edited all my PNG at this size, set my assets on libgdx and build my game apk.

And here is a screenshot of my gameboard ( don't pay attention at the differences of placing and objects, but check at the objets presents on both screenshot ).

As you can see, I have a loss of my PNG quality in the game.
It can be seen clealry on the hedgehog PNG, but also ( but not as obvious ) on the mushroom ( check at the outline ) and the hole PNG. If you really pay attention, on every objects, you can see pixels that are not visible on my first screenshot.

And I just can't figure out why this is happening Oo
If you have any ideas, you are very welcome !

Thanks.

PS : You can check more clearly the 2 gameboard on this two links ( look at them at 100%, display at high resolution ) :

Good quality link, from Illustrator

Poor quality link, from the game

Second phase of tests :

We display an object ( the hedgehog ) on our main menu screen to see how it looks like.
The things is that it looks like he is suppose to, which means, high quality with no pixels.

The hedgehog PNG is coming from an atlas :

layer.addActor(hedgehog);

No loss of quality with this method

So we think the problem is comming from the method we are using to display it on our gameboard :

blocks[9][3] = new Block(TextureUtils.hedgehog, new Vector2(9, 3));

the block is getting the size from the vector we are associating to it, but we have a loss of quality with this method.


texts: Preventing overlap in OnCollisionEnter2D

texts:
So I have successfully built a script that can determine the physics for a ball reflecting linearly off of walls, similar to pong, while the ball is using a kinematic rigidbody. The issue is when the ball hits the wall and the OnCollisionEnter2D is called, the ball has had it's position adjusted based on it's velocity such that it is phased inside the wall a tiny amount. My understanding is that this is necessary in order for the engine to recognize the collision. The ball seemingly reflects like normal, but in the uncommon event that the reflected angle allows the ball to travel while still having it's collider phased inside the wall, and the ball impacts a different surface of the wall, this 2nd impact will not result in the OnCollisionEnter2D call and the reflecting result, since technically the collider never left the wall in this time. This causes the ball to fly past the wall and off-screen.

I've tried many solutions to fix this, mainly making it so that before the bounce occurs but in the collision event, I would move the ball back to the precise location where the edge of the ball hit the edge of the wall. This would mean that the collider of the ball is in-bounds at all times and therefore no odd behavior as a result of overlapping would occur. I've yet to find a good method to do this, and I'm wondering if there is one that could be suggested to me or if there's a different solution entirely (which doesn't involve changing the ball's rigidbody from kinematic).

Below is the appropriate parts of the script I have written currently, as well as an image of what the game view looks like for visualization.

public class sword : MonoBehaviour {

public Rigidbody2D rb;
public CircleCollider2D coll;

public float speed;
public Vector2 trajectory;
public GameObject Player;

// Use this for initialization
void Start () {
    speed = 0.0f;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "player")
    {
        transform.position = new Vector2(-1000, -1000);
        Player.GetComponent<movement>().equipped = true;
    }
    if (collision.gameObject.tag == "solid")
    {
        ContactPoint2D otherObject = collision.contacts[0];
        Vector2 normal = otherObject.normal;
        trajectory = Vector2.Reflect(trajectory, normal);

    }
}

private void FixedUpdate()
{
    //constantly calculating new velocity
    rb.velocity = speed * trajectory;
    speed = speed * 0.93f; //drag
    if (speed < 0.0001f)
    {
        speed = 0.0f;
    }
    if (speed > 1)
    {
        Physics2D.IgnoreCollision(Player.GetComponent<CircleCollider2D>(), coll, true);
    }
    else
    {
        Physics2D.IgnoreCollision(Player.GetComponent<CircleCollider2D>(), coll, false);
    }
}

}

More Details: The sword in this image is what acts like the ball. My speed variable is set from a separate script. Everything is on the default layer. The Rigidbody for the ball it is kinematic, and for the walls it is static. Trajectory is a Vector2 that corresponds with the angular direction of the ball.


texts:
The game I am making runs at 60 fps, but occasionally it will drop lower than that. I want to limit the frame-rate to 30 fps so that those drops will be less noticeable.

I don't understand everything about this, so bear with me.
Here is what I have in the Initialize method:

IsFixedTimeStep = true;
TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0f);

All this is doing is making the game run in slow-motion.
What am I doing wrong?

Edit: I would like Update to be called the same number of times per second, but for Draw to be called only 30 times per second, instead of 60. How could this be accomplished?


texts:
I have a drawable, which I want to compare to. I created a drawable object with it, and when I log it with toString, I get:

android.graphics.drawable.BitmapDrawable@41f95548

I am randomly selecting a button, and I want to keep randomly selecting until the image of the image button is not android.graphics.drawable.BitmapDrawable@41f95548 Now, I want to compare using this code:

do{
}while(buttonBackground = android.graphics.drawable.BitmapDrawable@41f95548 ));

buttonBackground is a drawable object.

This, for some reason, gets me an error:

How can I compare images with a code like this android.graphics.drawable.BitmapDrawable@41f95548. What is this code called? Thanks


texts: How do I override a SteamVR Controller's transforms in Unity?

texts: I'm trying to provide an illusion to the user by rotating the controller about an arbitrary axis in the LateUpdate() method. But this doesn't seem to be having any effect as the controller probably is constantly getting updated by its real world location. Is there any way to override its real world position and orientation with a transformation in script?


texts: Is Update called based on screens refresh rate? MonoGame

texts: My game is running 60fps (Because I'm using a 60hz monitor) but if I would use a 85hz monitor it would be running 85fps. My question is if update is called based on the screens refresh rate or if its limited to 60 calls per second


texts: Problems in exporting terrain from autodesk 3ds

texts:
i am trying to make small counter strike sort of game and for the terrain part i have exported the terrain in 3ds format from Autodesk 3ds-max and imported the same in opengl using lib3ds. Its working fine but with few problems:

The terrain is mainly made up of some cubical boxes with texture on them and placed on a big flat surface with boundary wall. In opengl i have enabled anti aliasing but still there is too much aliasing on the boundaries (visible when rotating the camera).
I have tiled the floor with some image but in opengl it is just the single image stretched over the complete surface.
I have exported animated model (Skelton+mesh+material+animation) from 3ds and used cal3d library for reading the same. Model has a gun also which is not appearing in opengl and it too has too much of aliasing problem.

I have googled around but couldn't find any relevant solutions.

Thanks in advance


texts: Read actor instance's text variable for widget when triggered on different objects

texts:
What I'm trying to do:
(a 'long story version' is linked in comment below)
(and another user example is hyperlinked in comment below - i couldn't post over 8 images and/or links in this first comment*)
(there are other similar user questions elsewhere I know)
Short story: I'm trying to make a widget that is triggered by an actor blueprint, and I want the widget to display different text that reflects the public-variable-text edits I make in the editor.
My latest progress includes actors that are titled somewhat according to the hyperlinked user case above so, I have a "door_trigger" and a "doorWidget". I have altered the pin connections so much that I am just going to copy and paste all my screen shots below.
I got to change text asset DoorName by making a public variable called "name," as you'll see. I can make the trigger show this text on screen and have it disappear when the user leaves the trigger actor, BUT EVERY INSTANCE ALSO SHOWS THIS TEXT VALUE, EVEN THOUGH I CHANGE IT
In the screenshots (some in comment following too) you'll see the text "3" appear on screen, and it does this for all three of the dummy boxes I made; notice how the second box is supposed to show "dd" (I was just typing random filler content).
ALL HELP SO APPRECIATED!!!!! Thank you!!!


texts:
I have a custom entity class and what it does is create a SQUARE object.

public class Entity {
    Rectangle rect;

public Entity() {
    this.rect = new Rectangle(20,20);
    rect.relocate(200,200);
}

// I want it to be public Entity getEntity() {return this.rect;}
public Rectangle getEntity() {
    return this.rect;
  }
}

The problem is that I can't get my class to return an Entity object, instead of a Rectangle one.

How do I go about doing that?


texts: What does "GL_CLAMP_TO_EDGE should be used in NPOT textures" mean?

texts:
I have two sRGB PNG images I am using for textures. One is 64x64, and works fine. The other is 64x47, and when I attempt to use it I get an error:

reason: 'GL_CLAMP_TO_EDGE should be used in NPOT textures'

What does this mean, and how do I address it?


texts: How can I make the camera that follows my character position also follow the character rotation?

texts:
So I've tried to make the camera also follow my character rotation, I tried using the same process that I did for the position follow, using quaternion and transform.rotation but it was giving me some errors. Since I'm pretty new, I will ask for the best solution for my problem, here's the code:

void Start()
{
    followPos = transform.position - player.transform.position;
}

void LateUpdate()
{
    transform.position = player.transform.position + followPos;
}


texts:
Possible Duplicate:
  How to convert .max files to .egg on linux

Is there a way to load .max files directly to Panda3D engine? I am running Panda3D on linux so converting them using 3ds max is bit difficult.
Or at least is there a work around this problem?


texts:
I'm working on a project in XNA for WP7 with a low-poly environment, my problem is I need to setup a working per-polygon collision check between 2 or more 3d meshes.

I've checked tons of tutorials but all of them use bounding-boxes, bounding-spheres,rays etc., but what I really need is a VERY precise way of checking if the polygons of two distinct models have intersected or not.

If you could redirect me to an example or at least give me some pointers I would be grateful.


texts: Is a Stamina Bar (ala Dark Souls) a good idea for a casual player target group?

texts:
We all know the "Stamina Bar".
For those who dont: Its a "Bar" (usually right below your life-bar) which prevents spamming the attacks as much as you want.
Attacking will also reduce your stamina and you need a certain amount of stamina to use Attacks. Usually blocking , rolling and other things also require and reduce your stamina. Its a great way to balance the a real time action battle system. You can upgrade your stamina which is cool too because gives you a feeling of progress and add a little bit of fun there.

Anyway:

The Question here is:

Is this "okay" for "Casuals"?

I have a game which is open-world-ish and you can walk around and fight enemies and fight bosses too.
But the game seems "too easy" now. You can basically just spam your attack button and every enemy is easy.
Even the bosses.

A way the fix this is the stamina bar.

But wouldnt that overwhelm the casual players ?


texts: Optimization of linear solving for small matrices (10x10)

texts:
How to optimize the hell out of linear system solving for small matrices (10x10)? This would be used in an AR engine for a few games, but has to be done very fast.

This solver is to be executed in excess of 1 000 000 times in microseconds on an Intel CPU. I am talking to the extreme level of optimization used in graphiscs for computer games. No matter if I code it in assembly and architecture-specific, or study precision or reliability tradeoffs reductions and use floating point hacks (like many games, I use the -ffast-math compile flag, no problem). The solve can even fail for about 20% of the time!

Eigen's partialPivLu is the fastest in my current benchmark, outperforming LAPACK when optimized with -O3 and a good compiler. But now I am at the point of handcrafting a custom linear solver. Any advice would be greatly appreciated. I will make my final solution open source and share it here.


texts:
I am actually working on a general purpose pathfinding library (find it here), mostly oriented for grid-based maps.
I was looking for ways to integrate support for pathfinding with units of different sizes. Actually, I am working with the assumption that all units are square (i.e. their widths and heights in tile units are the same).

In researching, I came across a very comprehensive article about Annotated A-star, using True clearance values for pathfinding. I tried it, and succeeded in implementing it, and got it working with a wide range of search algorithms (A-star, Theta*, Dijkstra, DFS, Breadth-first search and Jump Point Search).

There are some small details of implementation I think I am still missing. First of all, when an agent is 2x2 sized (i.e it occupies 4 tiles on the grid map), what tile can be assumed to be the agent position ?  On the same page, clearance based pathfinding will fail in some cases. Let's consider the following map, where 0's are passable tiles, 1's are obstacles and x's matches walkable goal to be reached.
Let's assume we are pathing with a 2x2 sized unit:

00000000
00111100
001xx100
001xx100
00000000

For targets on the left (tiles 4,3 and 4,4), clearance value is 2, for both. No problem here. But for the others (tiles 5,3 and 5,4), clearance value is 1. So depending on how the agent position is taken, pathfinding will fail while obviously, for each of these target, the agent can properly fit into the dead-end space.

Another scenario, with the same 2x2 sized agent:

0000000x
0000000x
0000000x
0000000x
xxxxxxxx

Well, all tiles are walkable here, no obstacles. We want the object to reach any goal on the rightmost or bottom-most border. Each of these targets have a clearance of 1, so annotated pathfinding wil obviously fail here...depending on how the agent's position is taken.

How do I work around this issue?


texts: Particle friction with variable timestep in XNA

texts:
Alright, so I'm working on an engine of sorts in XNA (yes, it's deprecated, I know) and I'm implementing my own particle system. I've defined a "ParticleEffect" such that when it's supplied a GameTime and an IEnumerable<T:IParticle>, it applies an "effect" to every particle in that collection.

For example, my Friction effect:

public sealed class Particle2D_Friction : ParticleEffectBase<Particle2D>
{
    public float Magnitude { get; set; }
    public float StopThreshold { get; set; }

    public override void Apply(GameTime time, IEnumerable<Particle2D> particles)
    {
        if (Enabled)
        {
            if (particles != null)
            {
                float delta = time.GetDelta();
                float magnitude = MathHelper.Clamp(Magnitude, 0.00f, 1.00f);
                Vector2 result = Vector2.Zero;

                foreach (var particle in particles)
                    if (particle != null && particle.Alive)
                    {
                        result = particle.Velocity - (delta * (1.00f - magnitude) * particle.Velocity);
                        if (Math.Abs(result.X) <= StopThreshold) result.X = 0.00f;
                        if (Math.Abs(result.Y) <= StopThreshold) result.Y = 0.00f;
                        particle.Velocity = result;
                    }
            }
        }
    }
}

Unfortunately, it isn't behaving quite as well as I'd like it to, and I know the issue is linked to the delta time. I should mention that time.GetDelta() is an extension method that returns (float)time.ElapsedGameTime.TotalSeconds; as a shortcut.

Anyways, when I remove the delta, the effect is a rather strong, but it comes to an immediate stop when Magnitude is equal to 0.00f (retains 0% of velocity), while it moves indefinitely when equal to 1.00f (retains 100% of velocity). That's fine and that's how it should work.

When I add the delta to smooth it out, I encounter a problem. When Magnitude is equal to 1.00f, it retains 100% velocity as it should. However, when Magnitude is equal to 0.00f, it retains 1/60th of it's velocity instead of stopping. Of course, 1/60 is equal to 0.01666, which is the frames per second on the delta. But it's wrong.

I'm not sure how to fix this behavior. Any suggestions?


texts: What is an achievable way of setting content budgets (e.g. polygon count) for level content in a 3D title?

texts:
In answering this question for swquinn, the answer raised a more pertinent question that I'd like to hear answers to. I'll post our own strategy (promise I won't accept it as the answer), but I'd like to hear others.

Specifically: how do you go about setting a sensible budget for your content team. Usually one of the very first questions asked in a development is: what's our polygon budget? Of course, these days it's rare that vertex/poly count alone is the limiting factor, instead shader complexity, fill-rate, lighting complexity, all come into play.

What the content team want are some hard numbers / limits to work to such that they have a reasonable expectation that their content, once it actually gets into the engine, will not be too heavy. Given that 'it depends' isn't a particularly useful answer, I'd like to hear a strategy that allows me to give them workable limits without being a) misleading, or b) wrong.


texts: Can I slightly rotate a 2D vector (UV Edge) to more closely reflect the corresponding 3d vector?

texts:
I'm trying to get the difference between the 3D angle of two connected edges and their corresponding angle in 2D (mesh to UV space).  I would like to slightly rotate the angle in 2D to closer match the angle in 3D.  How do I rotate the 2D vectors to reflect this change?

Here's my current approach to get the angles:
3D angles:

dot3D = vectorA.dot(vectorB);  //normalized vectors
angle3D = acos(dot3D);

2D angles:

dot2D = vectorA.dot(vectorB);  //normalized
angle2D = acos(dot2D);

Angle difference:

angleDiff = angle3D - angle2D;

Rotation:

vectorC = vectorA - vectorB;
float deltaX = vectorC.x * cos(angleDiff) - vectorC.y * sin(angleDiff);
float deltaY = vectorC.x * sin(angleDiff) + vectorC.y * cose(angleDiff);
vectorA.x += deltaX;
vectorA.y += deltaY;


texts: Change localScale.x in Unity without creating a new Vector3

texts: Is it possible to change localScale.x in Unity without creating a new Vector3?


texts: Mipmaps for Automatically Generated Texture Objects

texts:
I want to generate mipmaps for textures generated by BitmapFont(FileHandle fontFile) constructor. Since it doesn't have that option, what can i do? Can I somehow deep copy the Texture object with mipmaps on or is there any other setting for using mipmaps after Texture object has already been initialized?

I want to use MipMapLinearLinear filter.


texts:
Im new to minecraft modding, but Im curious about the possibility of creating a mod such that players could set up a 'security camera' with its own viewport so that the player could 'see what the camera sees'. For example, imagine a minimap style window that displays the viewport of the camera you've setup.

Specific questions:

can you have a second viewport that isnt tied to the player?
Can you programmatically access a viewport? e.g. store the pixel values to a variable rather directly rendering to the screen.


texts: How do you avoid lag with Three.js and mousemove?

texts:
I'm trying to create a browser moba-like game using three.js. I'm using WASD for movement and the player rotation follows the mouse with mousemove then lookAt() the intersection.

The problem:

As I start to move the mouse rapidly and doing other stuff like movement or shooting the game starts to lag and slow noticeably.

How can I increase performance of the game, should I create a worker thread for the raycasting, use other movement technique (e.g. right click to move). What is your recommendation?

var mouseCallback = function(e){
  if(e.clientX >= renderer.domElement.clientWidth-2){
    mouse.x = 1;
  } else {
    mouse.x = ( e.clientX / renderer.domElement.clientWidth ) * 2 - 1;
  }
  if(e.clientY >=  renderer.domElement.clientHeight-2){
    mouse.y = -1;
  } else {
    mouse.y = - ( e.clientY / renderer.domElement.clientHeight ) * 2 + 1;
  }
  if(player){
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObject( terain );
    var direction;

    for(var i = 0; i< intersects.length;i++){
      direction = intersects[0].point;
    }

    if(direction){
      var focalPoint =
        new THREE.Vector3(
            direction.x,
            player.position.y,
            direction.z
            );
      player.lookAt(focalPoint);
    }
  }
}


texts: Non monobehaviour classes not working properly

texts:
I am trying to make a deck of cards in c# for use in Unity. But when i planned it I didn't think that 'Deck.cs' or 'Card.cs' would need to inherit from Monobehaviour.

I have written 3 classes (one is a Monobehaviour, 'Table.cs'). I thought these would work to make a pack of 52 cards.

I get a null reference exception when I try to access the specific card from the Debug.Log line.

Here are the three classes. (I wonder if I am using the 'new' keyword properly)

(Also Table.cs is the monobehaviour and is attached to a Cube called Table in my game scene. There are no other objects or components in the scene besides the default Light and Camera)

 using UnityEngine;

public class Table : MonoBehaviour
{
Deck deck;

private void Start()
{
    deck = new Deck();
    Debug.Log("card 9 = " + deck.cards[9].value);

}
}

and

public class Deck
{
public Card[] cards;

public Deck()
{
    cards = new Card[52];
    for (int suit = 0; suit < 4; suit++)
    {
        for (int val = 0; val < 14; val++)
        {
            Card c = new Card((Card.Suit)suit, val);
        }
    }
}
}

and

 public class Card
{
public enum Suit { HEARTS = 0, DIAMONDS = 1, SPADES = 2, CLUBS = 3 };
public Suit suit;
public int value;

public Card(Suit Suit, int Value)
{
    suit = Suit;
    value = Value;
}

}

The error i get is this: NullReferenceException: Object reference not set to an instance of an object
Table.Start () (at Assets/Scripts/Table.cs:12)

And also I first made Card a struct and that doesn't give me the error, but for some reason all the cards remain as HEARTS and value 0 .

Anybody see what I have done wrong? Any help would be great. Thanks!


texts: How can I avoid tight script coupling in Unity?

texts:
Some time ago I started working with Unity and I still struggle with the issue of tightly coupled scripts. How can I structure my code to avoid this problem?

For example:

I want to have health and death systems in separate scripts. I also want to have different interchangeable walking scripts that allow me to change the way the player character is moved (physics-based, inertial controls like in Mario versus tight, twitchy controls like in Super Meat Boy). The Health script needs to hold a reference to the Death script, so that it can trigger the Die() method when the players health reaches 0. The Death script should hold some reference to the walking script used, to disable walking on death (I'm tired of zombies).

I would normally create interfaces, like IWalking, IHealth and IDeath, so that I can change these elements at a whim  without breaking the rest of my code. I would have them set up by a separate script on the player object, say PlayerScriptDependancyInjector. Maybe that script would have public IWalking, IHealth and IDeath attributes, so that the dependencies can be set by the level designer from the inspector by dragging and dropping appropriate scripts.

That would allow me to simply add behaviors to game objects easily and not worry about hard-coded dependencies.

The problem in Unity

The problem is that in Unity I can't expose interfaces in the inspector, and if I write my own inspectors, the references wont get serialized, and it's a lot of unnecessary work. That's why I'm left with writing tightly-coupled code. My Death script exposes a reference to an InertiveWalking script. But if I decide I want the player character to control tightly, I cant just drag and drop the TightWalking script, I need to change the Death script. That sucks. I can deal with it, but my soul cries every time I do something like this.

Whats the preferred alternative to interfaces in Unity? How do I fix this problem? I found this, but it tells me what I already know, and it does not tell me how to do that in Unity! This too discusses what should be done, not how, it does not address the issue of tight coupling between scripts.

All in all I feel those are written for people who came to Unity with a game design background who just learn how to code, and there is very little resources on Unity for regular developers. Is there any standard way to structure your code in Unity, or do I have to figure out my own method?


texts: How to avoid gimbal lock in Unreal Engine (c++)?

texts:
I created an orbit camera (sometimes called turntable camera; similar to the one with the "use UE3 orbit controls" setting in a static mesh view).

I attached the camera to a USpringArmComponent with a TargetArmLength set to 400.
In the tick function, I rotate the arm with this simple method:

        // Simple, clamped version
        FRotator Rotation = CameraSpringArm->GetComponentRotation();
        Rotation.Yaw += CameraInput.X * CameraRotationSpeed;
        Rotation.Pitch = FMath::Clamp(Rotation.Pitch + CameraInput.Y * CameraRotationSpeed, -85.0f, 85.0f);
        CameraSpringArm->SetRelativeRotation(Rotation);

I had to clamp the pitch to hide the gimbal lock problem. But this prevent users to rotate completely around objects.
I don't understand why the Z rotation (the yaw) occurs on the world z axis ( FVector::UpVector which is (0, 0, 1)) and not on the local z axis. It turns out that this is exactly what I want.

I tried to solve this gimbal lock problem with this other method:

        // Taken from https://answers.unrealengine.com/questions/232923/how-can-i-avoid-gimbal-lock-in-code.html
        FRotator RotationDelta(CameraInput.Y * CameraRotationSpeed, CameraInput.X * CameraRotationSpeed, 0.f);
        FTransform NewTransform = CameraSpringArm->GetComponentTransform();
        NewTransform.ConcatenateRotation(RotationDelta.Quaternion());
        NewTransform.NormalizeRotation();
        CameraSpringArm->SetWorldTransform(NewTransform);

It works, but this time, the Z rotation (yaw) occurs on the local Z axis. How can I change it to rotate around the world Z axis, and the local Y axis, without gimbal lock?

I tried this hybrid solution, but the gimbal lock is still there:

        // Hybrid
        FRotator RotationDelta(CameraInput.Y * CameraRotationSpeed, 0.f, 0.f);
        FTransform Transform = CameraSpringArm->GetComponentTransform();
        FRotator Rotation = CameraSpringArm->GetComponentRotation();
        Rotation.Yaw += CameraInput.X * CameraRotationSpeed;
        Transform.SetRotation(Rotation.Quaternion());
        Transform.ConcatenateRotation(RotationDelta.Quaternion());
        Transform.NormalizeRotation();
        CameraSpringArm->SetWorldTransform(Transform);

I did solve this problem (a long time ago) in OpenGL using quaternions, so I tried this version:

        // Quaternion
        FRotator Rotator = CameraSpringArm->GetComponentRotation();
        FQuat Quaternion = Rotator.Quaternion();
        // Rotate around the world Z axis:
        Quaternion *= FQuat(FVector::UpVector, FMath::DegreesToRadians(CameraInput.X * CameraRotationSpeed));
        // Rotate around the local Y axis:
        Quaternion *= FQuat(Rotation.RotateVector(FVector::RightVector), FMath::DegreesToRadians(CameraInput.Y * CameraRotationSpeed));
        CameraSpringArm->SetRelativeTransform(Quaternion);

But this does not work. I also tried this:

        // Quaternion + transform
        FTransform Transform = CameraSpringArm->GetComponentTransform();
        Transform.ConcatenateRotation(FQuat(FVector::UpVector, FMath::DegreesToRadians(CameraInput.X * CameraRotationSpeed)));
        Transform.ConcatenateRotation(FQuat(Rotation.RotateVector(FVector::RightVector), FMath::DegreesToRadians(CameraInput.Y * CameraRotationSpeed)));
        Transform.NormalizeRotation();
        CameraSpringArm->SetWorldTransform(Transform);

without success.


texts: I've heard about ambient occlusion and it looks nice, but what exactly is it?


texts:
Imagine a (3D) game like Railroad Tycoon 3. Player selects a rail track, clicks LMB and drags the mouse to the end position. During this drag, the rail track model scales and adopts to the landscape, so user sees the resulting track in dynamic.

The question: how this can be done? A brief idea/links/sketches will be enough. I just don't know how to start (I'm novice game developer). If it is matter, I use Unity as a game engine.

Thanks in advance.


texts: A 2D Camera Follow Script That Does Not Rotate?

texts:
I am attempting to make a 2D racing game. So far I have a player car (sprite) and a main camera.

I would like to know how to make the main camera follow the player car while still showing signs of movement (I don't want the positions to match exactly in the middle of the screen).

My Player Car has a Rigidbody2D and a MoveCar script

using UnityEngine;
using System.Collections;

public class MoveCar : MonoBehaviour {

    public float speed = 10f;
    public float gravity = 0f;

    void CarMove ()
    {
        if(Input.GetKey(KeyCode.RightArrow))
        {
            transform.Translate(Vector2.right * speed * Time.deltaTime);
        }
    }

    // Update is called once per frame
    void Update ()
    {
        CarMove();
    }
}

Then there is my Main Camera, its projection is switched to Orthographic and has default settings as well as a FollowCar script:

using UnityEngine;
using System.Collections;

public class FollowCar : MonoBehaviour {

    public Transform player;

    public GameObject other;
    public Rigidbody2D rb = other.GetComponent<Rigidbody2D>;

    void Update()
    {
        transform.Translate(Vector2.right * .5f * Time.deltaTime);
        Vector2.MoveTowards( Vector2 , Vector2 player,
    }
}

I would like to know where to go next or if I'm even going in the right direction. I have no idea how to utilize the MoveTowards() function.


texts:
This question might be naive, I'm just making sure I grasp the API. Suppose you have an array of 3 objects

Is array.get(o) the same as array.first(); and array.get(2) the
same as array.peek()?

Suppose you have an object moving on screen

Is array.get(o).x the same as array.get(o).getX()

By reading the API it seems to me that x returns position of the object while getX() returns the position of the mouse, or the user's finger whenever he touched the screen. But if that's true then I shouldn't be allowed to use getX() on an object like I did above


texts:
I have some code that essentially draws a column on the screen of a wall in a raycasting-type 3d engine. I am trying to optimize it, as it takes about 10 milliseconds do draw a million pixels using this, and the vast majority of game time is spent in this loop. However, I don't quite understand what's occurring, particularly the recasting (I modified the "pixel manipulation" sample code from the SDL documentation). "canvas" is the surface I am drawing to, and "hello" is the surface containing the texture for the column.

    int c = (curcol)* canvas->format->BytesPerPixel;
    void *canvaspixels = canvas->pixels;
    Uint16 texpitch = hello->pitch;
    int lim = (drawheight +startdraw) * canvpitch +c + (int) canvaspixels;
    Uint8 *k = (Uint8 *)hello->pixels + (hit)* hello->format->BytesPerPixel;

    for (int j= (startdraw)*(canvpitch)+c + (int) canvaspixels; (j< lim); j+= canvpitch){
        Uint8 *q = (Uint8 *) ((int(h))*(texpitch)+k);
        *(Uint32 *)j = *(Uint32 *)q;
        h += s;
    }

We have void pointers (not sure how those are even represented), 8, 16, and 32 bit ints (h and s are floats), all being intermingled, and while it works, it is quite confusing.


texts: Is there a wall building tool in unity3d?

texts: I'm currently building a maze game in unity 3d and after building a few levels by placing and repositioning cubes by hand as walls, I think, that it would be nice if there was a tool to place walls, which are cubes with constant height and width, but have different length and rotations on the y-axis, by joints: you click to place a joint, and a wall goes in straight lines beetwen joints. So is there a tool like that?


texts: How would I generate random falling objects

texts: I'm creating a game using libgdx on Eclipse that is similar to Ragdoll Avalanche.  I'm looking for a way to generate falling objects like the triangles of Ragdoll Avalanche.  All I know that i have to use an array but i dont know how to do it.


texts: LibGDX: Can i get some useful tips for loading textures?

texts:
So basically in my game(completely new to gave dev) I have a level select screen. I have 8 Buttons to select the levels and i use an asset manager to load the textures for the buttons. For example their is a locked button for when you have unlocked the level, an active for when your mouse is over the button and inactive when your mouse is not over it. My problem is that having all these textures keep interchanging is causing memory usage to go off the charts, from as low as 30mb all the way over 1000mb as soon as i go to the level select screen and it keeps rising. Whats a good way to load lots of textures without having to use so much memory? Or should i just figure out a better way to load them without causing so much usage of memory. Im new to this so go easy on me :)

or... Would this amount of memory being sprung be a memory leak somewhere?

Edit: Heres the code snippet where the memory leak i traced to i believe.

I'm calling this method in my handleInput which i then call in the render method.

public void levelManager(float rowX, float rowY, Screen setScreen, Texture drawActive, Texture drawInactive,
        float multiplier) {
    if (Gdx.input.getX() / GravitySpikesRevamped.PPM < (rowX + BUTTON_WIDTH) / GravitySpikesRevamped.PPM
            && Gdx.input.getX() / GravitySpikesRevamped.PPM > rowX / GravitySpikesRevamped.PPM
            && (GravitySpikesRevamped.GAME_HEIGHT - Gdx.input.getY())
                    / GravitySpikesRevamped.PPM < (rowY + BUTTON_HEIGHT) / GravitySpikesRevamped.PPM
            && (GravitySpikesRevamped.GAME_HEIGHT - Gdx.input.getY()) / GravitySpikesRevamped.PPM > rowY
                    / GravitySpikesRevamped.PPM) {

        if (multiplier == 1) {
            game.batch.draw(drawActive, BUTTON_WIDTH / 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 2) {
            game.batch.draw(drawActive, BUTTON_WIDTH * 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 3) {
            game.batch.draw(drawActive, BUTTON_WIDTH * 3.5f / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        }

        if (Gdx.input.isTouched()) {
            game.setScreen(setScreen);
        }
    } else {

        if (multiplier == 1) {
            game.batch.draw(drawInactive, BUTTON_WIDTH / 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 2) {
            game.batch.draw(drawInactive, BUTTON_WIDTH * 2 / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        } else if (multiplier == 3) {
            game.batch.draw(drawInactive, BUTTON_WIDTH * 3.5f / GravitySpikesRevamped.PPM,
                    rowY / GravitySpikesRevamped.PPM, BUTTON_WIDTH / GravitySpikesRevamped.PPM,
                    BUTTON_HEIGHT / GravitySpikesRevamped.PPM);
        }
    }

Okay i solved it, basically in my method above every time i called it was creating a new screen. So i basically was creating infinite amount screens in memory. I fixed it :]


texts: Projecting Coordinates from one Space into another, but with "twisting"

texts:
i'm trying to generate a decal mesh kinda like this: http://blog.wolfire.com/2009/06/how-to-project-decals/

but instead of projecting the decal with a box, i need to project it with a sort of triangular space. the "decal space" will have a start triangle and an end triangle. the end triangle isn't necessarily the same size as the start triangle and it isn't necessarily parallel to it and it can be rotated.

i need to be able to transform coordinates into that space and back out. how can i do that? can you do that with a normal 4x4 matrix?


texts:
For the past two weeks I was trying to make a map maker for my java ME 2D RPG game. I failed because i get errors using slick TWL and the forum for this is inactive.

So I just wondered is there anyone that knows slick TWL (Themable Widget Library)? Or maybe do you know a good MapMaker where i could upload my map elements build a map and get numbers to use them for building map with LayerManager class?

Already found one http://sourceforge.net/projects/tilemapeditor2d/. But the thing is my map elements are in different .png images. In one of those images there is 16 elements (trees water and etc) and those kind of images are 29. So it would be hard to build a map with LayerManager

Well I was thinking putting everything into one image and that way it would be simplier.


texts: World Bounds - (0, Size) or (-HalfSize, HalfSize)?

texts:
When creating a game space in which to move, draw and collide objects, is it better to have the (0,0) point, or the (0,0,0) point, be in the very center of your space, such that the bounds of the worlds are (-halfSize, halfSize), or is it better to have it be at the far corner of your space, so the bounds are (0, size)?

What are the pros and cons of each, and what sort of problems do they each entail?  Or does it really just not matter?

It seems like a minor detail, but I wanted to see if there were perhaps major issues I might be overlooking.


texts: Half-shaded pixel artifacts on 2d dynamic lighting shader

texts:
I'm working on a shader for dynamic lighting in a 2 unity game. I'm new to shaders but I've managed to get something close to the effect I was looking for, although not 100%.

As you can see in the image below, my texture maps respond to a point light and are shaded using a cel-shaded technique:

However, if you look closely, you can see that a few of the pixels are somewhere between fully lit and half lit, creating diagonal lines across pixels:

What I would like to achieve instead, are pixels that have a single color at all times, depending on the intensity of the light reaching it.

Do I need to move away from the surface shader and implement the lighting in a vertex+fragment shader?

Below is the relevant code for the shader:

Shader "Custom/PixelCellShading"
{
    ...

    SubShader
    {
        Tags { "RenderType" = "Cutout" }

        CGPROGRAM
        #pragma surface surfaceFunction PixelCell alpha
        #pragma target 3.0

        sampler2D _MainTex;
        sampler2D _NormalTex;
        float _Cels; // number of shading levels, set to 3

        struct Input
        {
            float2 uv_MainTex;
        };

        void surfaceFunction(Input IN, inout SurfaceOutput o)
        {
            float3 normalMap = UnpackNormal(tex2D(_NormalTex, IN.uv_MainTex));
            fixed4 c = tex2D(_MainTex, IN.uv_MainTex);

            o.Normal = normalMap.rgb;
            o.Albedo = c.rgb;
            o.Alpha = c.a;
        }

        half4 LightingPixelCell(SurfaceOutput s, half3 lightDir, half attenuation)
        {
            half NdotL = dot(s.Normal, lightDir);
            half cel = floor(NdotL * _Cels) / (_Cels);

            half4 c;
            c.rgb = s.Albedo * _LightColor0.rgb * cel * attenuation;
            c.a = s.Alpha;
            return c;
        }
        ENDCG
    }
}


texts:
The way cartesian coordinations are presented and used is kinda confusing.

When working with 2D the vertical axis is Y, though when working with 3D the vertical axis is Z and Y becomes the "depth" axis.

Basically I'm thinking the correct way, and best way would be to use the layout of axis.

Though Blender (3D modelling program) and other program, a lot games, present the axis in the "weird order" (my opinion)

Also if you read on Wikipedia about cartesian coordinates, your are presented with that layout of axis.

Wikipedia Cartesian Coordinates

Is there any specific or logical reason for this "flip" of axis?


texts: Using 2d sprite characters from asset store

texts:
noob here

So I recently downloaded this asset https://assetstore.unity.com/packages/2d/characters/2d-archers-sprites-18748
from the asset store. All the animations work great (walk, jump etc) but I do not know how to edit these. So let's say I want my character to jump from point A to point B, how would i start doing this? And would i just add the script to the animation?


texts:
How does one setup the game space for a game so that obstacles can be spawned?

Examples would be ice climber or the iphone doodle jump. Tile maps are limited in size and would need to change often if the user jumps a lot.

How would this be done in another way than tile maps.

How or what is used to create the notion of a game world where these spawned ledges/obstacles are placed as the user progresses through the stage?

What is actually moving if the user jumps from ledge to ledge, what are the ledges based on in terms of the game world/space. What data structure or representation could the game use to reference and manage the spawning of these obstacles/ledges?

How is a continuous environment created which creates collision objects as the user progresses?


texts: How can I do something only once In Update function?

texts:
when I do something In Update():

void Update(){
Debug.Log("Hello World");
}

I have this output:

Hello World
Hello World
.
.
.
Hello World

but Instead of printing manytimes I need a way that print Hello World once.


texts: Is there a simple 2D Android barebones starter project?

texts:
I'm looking at creating a tower-defence-style game on Android, developed in Java. I'm spending a lot of time trying to just get a background image (drawn onto a canvas) that pans/zooms within the bounds of the screen etc. that I will eventually draw my game onto.

It seems to be a lot of work just to get theses basics working correctly. Is there a simple barebones project that has this stuff taken care of that I can build my game on top of?


texts: How do I decrease the scale of an instanced node or scene?

texts:
I'm trying to decrease size of instanced RigidBody2D scene, through code. With scale(), I'm trying to decrease the size of the image/sprite that's attached to the RigidBody2D. The problem is, it's not working.

No matter how much I try to scale down, the size of the blood drop circle remains the same.

const blood_druple_scn = preload("res://Scenes/blood.tscn")

func spawnBlood():
    var newBlood = Blood_druple_scn.instance()

    rotationAdd = rotationAdd + 30

    if(switchBloodSize == 0):
        set_scale(Vector2(2,1)) //This part is my problem
        print("blood size: ", newBlood.get_scale())
        add_child(newBlood)
        switchBloodSize = 1

    elif(switchBloodSize == 1):
        newBlood.scale(Vector2(0.5,0.5)) //This part is my problem
        print("Blood size: ", newBlood.get_scale())
        add_child(newBlood)
        switchBloodSize = 0

    newBlood.set_pos(Vector2(100,100))
    rotate(rotationAdd)

As you can see, I have two different if conditions, each with a different scale() and size. Sadly, both remain the same size. The strange part is that it does display the scale values as been altered, yet the newBlood instance is not visually changing. Why is this?


texts:
I have a short snippet that's rotating the meshes of the wheels as I'm driving forward, but it's also rotating wheels to match the direction I'm turning, and I wish to turn this off completely.

        Quaternion quat;
        Vector3 position;
        m_WheelColliders[i].GetWorldPose(out position, out quat);
        m_WheelMeshes[i].transform.position = position;
        m_WheelMeshes[i].transform.rotation = quat;

How would I lock what angles I don't want the wheel meshes rotating?


texts: Box2D platformer: Why does horizontal movement stop jumping?

texts:
I'm writing my sBox2D game character's movement code, but my implementation of jumping is failing:

When I press the Jump key, the character jumps OK. However, when I press jump and another key (like the left arrow key) at the same time, it kind of blocks the jump from happening.

I'm using applyForceToCenter and setLinearVelocity to move the character.

What could the problem be?

Here's how I've bound keys trigger movement:

// press W key (aka Up key or BTNup)
if (RHInput.isDown(RHInput.BTNup)) {

    if(rhcl.isPlayerOnGround()) {
        toniBody.applyForceToCenter(0, 100, true );
        System.out.println("Toni jumps");
    }
}

// press A key (aka Left key or BTNleft)
if (RHInput.isDown(RHInput.BTNleft)) {

    if(rhcl.isPlayerOnGround()) {
        toniBody.setLinearVelocity(-5, 0);
        System.out.println("Toni walks left");
    }
    else {
        toniBody.setLinearVelocity(-1, 0);
    }
}


texts: How can I easily create/edit a level for a scrolling shooter game?

texts:
I've been asking this question over the years many a time, but I still haven't found an answer when i search for one. Now I have slightly more knowledge of how programming is done and want to start making some full games.

I want to start with a side scrolling shooter (space style like R-Type/Gradius). I have many ideas in my head for good levels, and i even have some basic 3d skills in Maya/Blender to make the assets, but I do not know how best to formulate the levels. Lets say the space shooter has 30 levels. Each level might have about 10-15 enemy types and a boss on some levels. How best to store the location of all the enemies? (Same scenario for all the background objects,obstacles, powerup locations etc.)

Is there a better way than manually building the whole level in a Unity Scene editor view? Another way I have tried is to set spawn positions for every single object as a Vector2 or similar in XML or JSON, but how i did it that seemed even harder to make the levels than just inside the editor (not even accounting for having to write the functionality to get the data from the textfile).


texts:
I asked a similar question to this yesterday and gained some knowhow but
I'm a little confused:

If I have many quads that contain vertices and indices that are positioned to to form a bigger picture, then that bigger picture is positioned using world matrices...

How do I draw them all? From what I've gathered I've got to do in it in one pass for good speed.

I used to draw every quad with its own pass. Now every quad in an object is drawn in one pass.

But if I have a lot of objects it will slow down.

So my question is: how does one go about drawing lots of separate vertices and indices without losing frame rate? I don't need someone to hold my hand just maybe point in the right direction.


texts: IgnoreCollision while Dodging & Colliding

texts:
I'm working on a mechanic to allow the player to dodge through enemies. However I'm running into the issue where the player is only able to dodge through enemies while their already dodging when they collide with the enemy.

I want this to work both ways, as in, when their colliding with the enemy, they should be able to dodge through then.

Here's what I've been trying:

void OnCollisionEnter (Collision col) {

    //    STOP ENEMY FROM MOVING/PUSHING
    if (col.gameObject.tag == "Enemy") {
        Debug.Log("Collided with: " + col.gameObject.name);
        target = col.gameObject;
        target.GetComponent<ZombieController>().mRigidbody.isKinematic = true;

        //    IGNORE DODGING COLLISION WHEN ALREADY COLLIDED
        if (isDodging) Physics.IgnoreCollision(col.collider, GetComponent<Collider>(), true);
    }

    /*    IGNORE DODGING COLLISION
    if (isDodging && col.gameObject.tag == "Enemy") {
        Physics.IgnoreCollision(col.collider, GetComponent<Collider>(), true);
    }*/

}

It just doesn't seem to work when the player has already collided with the enemy. Hopefully all that made sense.


texts: Unity Mirror Shader double image in HTC Vive / Steam VR

texts: I'm implementing a mirror in Unity for SteamVR / HTC Vive. I'm using the mirror reflection shader for Unity. It looks fine, overall, but the left eye and right eye don't align unfortunately, so it's creating double image. How do I resolve it?


texts: Animator get number of animations (Unity)

texts:
In C#, how would I get the number of animations in an Animator Controller?

So I want to find out how many animations there are in an Animator Controller, and have this number in script.

Thanks in advance!


texts: How can I draw some of my XNA models semi-transparent? (C#, XNA 4.0)

texts:
I've recently made some basic Blender models without transparency for a new game I've been working on, but I'm having some problems rendering them semi-transparently. Namely, I haven't been able to figure out how to render them semi-transparent at all.

I've looked around quite a bit for code samples, and for some reason I just can't find anything that fits. I figure transparency probably has to do with BlendState.AlphaBlend somehow, but I'm not sure how exactly.

My models are simple VertexPositionColor models that consist of a single mesh. I've tried turning transparency on in the material in blender, but it doesn't seem to do anything when I render it again in C#. (Except make it appear transparent in blender) Also - I'm not looking for anything fancy like a crystal-like effect that requires making my model more than one mesh, just something simple and effective that will make my models at least able to be seen through.

So basically, my questions are:

How can I render an opaque VertexPositionColor model at a given percent transparent?
Is there a non-shader solution to my problem?
Is there a code sample anywhere for doing model transparency in XNA 4.0?

Thanks!


texts: Translating Steering Behaviour Pursuit sample

texts:
I've come across a C++ Sample of from Programming Game AI by Example. For the most part it is fairly understandable, the only thing confusing me is the reference to "m_pVehicle->Heading()" I'm not sure what it means by heading. If anyone could clarify this, I would really appreciate it.

 Vector2D SteeringBehaviors::Pursuit(const Vehicle* evader)
    {
      //if the evader is ahead and facing the agent then we can just seek
      //for the evader's current position.
      Vector2D ToEvader = evader->Pos() - m_pVehicle->Pos();

      double RelativeHeading = m_pVehicle->Heading().Dot(evader->Heading());

      if ((ToEvader.Dot(m_pVehicle->Heading()) > 0) &&
          (RelativeHeading < -0.95))  //acos(0.95)=18 degs
      {
        return Seek(evader->Pos());
      }

      //Not considered ahead so we predict where the evader will be.

      //the look-ahead time is proportional to the distance between the evader
      //and the pursuer; and is inversely proportional to the sum of the
      //agents' velocities
      double LookAheadTime = ToEvader.Length() /
                            (m_pVehicle->MaxSpeed() + evader->Speed());

      //now seek to the predicted future position of the evader
      return Seek(evader->Pos() + evader->Velocity() * LookAheadTime);
    }


texts: How do I go about selecting minimum GPU requirements for a video game a couple years out from release?

texts:
How does one go about determining a good minimum GPU requirement for a game that development is starting on, that will be published in approximately 2 years?

On one hand, you want as many people as possible to be able to play it, but on the other hand, you want the capabilities to be as high as possible for a better experience. The higher the DX/GL API you can use also means some things will be much better optimized.

My current idea is basically to identify what GPUs of the past have done, over a two year period, and identify the best one at the moment that will more than likely be hitting the bargain bin at the expected release date.


texts:
I've got my own game engine, now rendering and animating, MD2 MD3 and MD5 models now. I feel i am only just starting to get comfortable with opengl.

I'm currently writing code to render Quake 3 maps now too but, i would love to know how games like red faction allowed for destructible environments. Not quite sure, where to start with this. If i render a map do i have to turn the map into constitute components where by a physics engine controls every brick in the map or something maybe someone could tell me where i should look or read would be great. Thanks.


texts:
I'm trying to create a fog effect like civ 5:

I tried creating a StencilSet shader that receives a mask and sets the stencil buffer to 1. I would render the following on every unexplored tile using this shader. White is full alpha, black is 0 alpha, gray is in between.

Then I created a StencilUse shader that would display the cloud as one big texture, but will test that stencil value is 1. This way the cloud will only be shown on top of the unexplored tiles (+ a bit of overlap outside the tile, per the mask sprite).

This is what I got:

The problem is that I can't produce the fading effects towards the end of the cloud. It's either fully visible or not visible at all. How would I be able to use the grey areas when determining the alpha value of the cloud?

Any ideas?
(I'm using Unity)


texts: How to correctly pass multiple light structures to shader stage?

texts:
I'm having some problems when passing multiple light structures to a shader stage. I'm using an array of point lights that is updated each frame.

This is my code for creating the buffer

D3D11_BUFFER_DESC lbDesc;
lbDesc.ByteWidth            = sizeof( PointLightData ) * NUM_LIGHTS;
lbDesc.Usage                = D3D11_USAGE_DYNAMIC;
lbDesc.BindFlags            = D3D11_BIND_CONSTANT_BUFFER;
lbDesc.CPUAccessFlags       = D3D11_CPU_ACCESS_WRITE;
lbDesc.MiscFlags            = 0;
lbDesc.StructureByteStride  = 0;

hr = mDevice->CreateBuffer( &lbDesc, nullptr, &mLightBuffer );

And this is how I update it

D3D11_MAPPED_SUBRESOURCE mappedResource;
hr = mDeviceContext->Map( mLightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );

if( SUCCEEDED( hr ) )
{
    memcpy( mappedResource.pData, &mPointLightData[0], sizeof(PointLightData) * NUM_LIGHTS );
    mDeviceContext->Unmap( mLightBuffer, 0 );
}

mPointLightData is declared like this

mPointLightData = new PointLightData[NUM_LIGHTS];

In my shader I declare the light

struct PointLight
{
    float4  positionAndRadius;
    float4  ambient;
    float4  diffuse;
    float4  specular;
    float3  attenuation;
};

cbuffer CB_LIGHT : register(b1)
{
    PointLight  pointLight[2];
};

I can only access the first light object in the buffer successfully. Rendering the second light results in a pitch black scene.

However, if I change the starting address at the mapping stage from &mPointLightData[0]  to  &mPointLightData[1] the second light works but obviously not the first.

So my guess is that I'm doing simething wrong at either the mapping stage or at the creation of the buffer..

Any suggestions? Thank you!


texts: How can I detect a clicked element in an Editor Script?

texts: I want to implement a custom LayoutManager, e.g. a HorizontalLayout. (Yes I know, that this already exists, but I want my own behaviour) So when I let my script calculate the width, that works. But now I want to adjust the width of one Element and let the script recalculate the width of the other elements accordingly, I run into the problem, that the width is "locked" because the script is calculating all the time. So I want to tell the script, that it should only recalculate for the elements which are not clicked on the layout for the moment. I hope something like this is possible.


texts: Alpha Blending in Software with Gamma Correction

texts:
How does one efficiently implement alpha blending, without botching gamma?

Alpha blending is basically the following expression:

result_color = (dst_color*src_alpha - dst_color*src_alpha*dst_alpha + src_color - src_color*src_alpha)/(1 - src_alpha*dst_alpha)
result_alpha = src_alpha*dst_alpha

The formula is unusual because I use inverted alpha, where 0 means opaque and 1 - completely transparent. Rationale: many CPUs have instruction to compare with zero, but no instruction to compare with 0xff000000. Also, I can pass just 0xRRGGBB to set_pixel instead of 0xffRRGGBB for opaque color.

For gamma-packed 8-bit RGB I've managed to implement that expression somewhat efficiently in early 90ies style code:

void ablend(int dr,int dg,int db,int da, int *sr,int *sg,int *sb,int *sa) {
  int ya = (da * *sa)>>8;
  uint32_t d = idiv_lut[255 - ya];
  uint8_t *st = ab_lut[255 - *sa];
  uint8_t *dt = ab_lut[*sa - ya];
  *sr = ((dt[dr] + st[*sr])*d)>>8;
  *sg = ((dt[dg] + st[*sg])*d)>>8;
  *sb = ((dt[db] + st[*sb])*d)>>8;
  *sa = ya;
}

Obviously working with RGB, without unpacking it first, produces incorrect result (it is the most common graphics programming pitfall), so they must be unpacked (i.e. pow(x,2.2)), and now one can't use ab_lut anymore, because it would require 2^30 bytes, and replacing division with multiplication would be impossible on a 32-bit system either.

Give that, this question implies some side questions:

Is using float the only solution for unpacked RGB processing?
How can I perform alpha blending with gamma correction?
Is it worth it (L1 cache-wise) to still use gamma packed sRGB, instead of a simple array of 4 32-bit float R,G,B,A components, or would memory access become a bottleneck on a majority of CPUs?

So maybe I just have this 90's mindset, where keeping data size small meant difference between 1 and 60 frames per second, and today we can safely use as many additional bytes as required?


texts: "Hold to jump higher" suddenly outputs a much higher jump

texts:
I'm programming my first game in Unity and I'd like to make a very controllable jump.

The idea is to apply an upward force while the player is still pressing the jump button, and then after some time ignore jump input. Kinda like how Mario and Mega Man jump.

Problem is, somehow, my character occasionaly jumps much higher than it normally does.

I set three variables on the inspector:

jumpImpulse: the initial speed after pressing the jump button;
riseAcc: the acceleration applied to the character while holding the jump button;
maxJumpHoldTime: the longest possible time one might hold the button while still rising.

if ((onGround || onPlatform) && Input.GetButtonDown("Jump")){ //GetButtonDown prevents holding jump and keeping jumping

    rb.AddForce(Vector2(0,(jumpImpulse/rb.mass)), ForceMode2D.Impulse); //force that starts the jump itself.
                                //  /rb.mass makes F=ma into F=ma/m ==> F = a, so "Force" is actually acceleration.
                                //  This is to better control mass and jump mechanics.
    jumping = true;

    //DEBUG
    debugJumped = true;
}

if (jumping && Input.GetButton("Jump")){

    rb.AddForce(Vector2(0,(riseAcc/rb.mass)), ForceMode2D.Force); //first acceleration

    jumpHoldTime += Time.deltaTime;

    if (jumpHoldTime >= maxJumpHoldTime) {
        jumping = false;
    }

} else {

    jumping = false;
    jumpHoldTime = 0;

}

//Made this so I know how high the character jumps.
if (debugJumped && (!onGround) && rb.velocity.y <= 0){
    Debug.Log ("Jump height is: " + transform.position.y);
    debugJumped = false;
}

In the console, the jump height is listed normally as 2.376213, but sometimes it appears as 5.008272. It appeared once as 2.377432. Also, this variation seems to appear more frequently when I'm also moving the character left or right.

And I'm not sure if this is related, but there are many times when I press the jump button and the character simply doesn't jump.

Also, I put everything here under the FixedUpdate function.


texts: Advice on how to store level design info?

texts:
I'm building a 2D tile-based puzzle game in C#, using Monogame. The game board is an 8x6 grid of tiles, each of which can contain a number of objects. Conveniently, the number of possibilities for what each tile can contain fits nicely into 1 byte. I was wondering what the most sensible way to store level design data would be. I'd like it to be at least vaguely human-editable, as I need to construct a level or two while I build the game. Once I'm sure the game logic is all working and it's playable, I intend to build a level editor to construct the rest of the levels, but I need to build the first few manually.

Currently I'm tempted by the idea of encoding the levels in the colour data of an 8x6 pixel bitmap, but that's possibly overkill. Thoughts?


texts: How to achieve 2D ski movements similar to Alto Adventure?

texts:
I'm trying to achieve 2d movement similar to Alto's Adventure with Unity 2D. When grounded I want the character to slide alone the terrain parallel to the slope, but I want to be able to freely rotate the character in mid air. In my current failed implementation I tried using a 2d collider attached to an gameobject with a movement custom script. I'm using vertical and horizotal raycast to detect the slopes, and the object rotates based on the angle of the slope. Long story short I've given up on this implementation for now.

Do you guys have any suggestions or pointers on achieving this type of movement?


texts: XNA Entity Component Design: Lost on how to include Sprite Animation

texts:
I've been reading about Entity Component design and thought it's pretty neat.
I've been trying to write a quick 2D engine in XNA.

I think I've laid the proper groundwork for registering and updating entities, since I've created some "PositionComponents" that seem to work with my Camera Entity (an Entity that simply owns ZoomableComponent, PositionComponent, MouseInputComponent).

All the tutorials seem to however seem to end at this stage of design.
I'm pretty lose now on how I would like to design my animation/sprite components.

I know I want some sort of 'RenderableComponent' which you assign it a Texture
I need some sort of FSM (Finite State Machine) to hold Entity States
I need some sort of Animation Manager.

Does anyone have any tips?


texts: Destroy() does not work inside OnBecameInvisible()

texts:
I'm trying to destroy an object when it's out of the camera's view.

My code works correctly on every object in the scene, but when I'm creating an object from a prefab using Instantiate(), it doesn't works!

Here's Sv_Generator.cs

public class Sv_Generator : MonoBehaviour {
   public GameObject generator_proxy;
   public GameObject object_prefab;

    void Update () {
         GameObject new_object = (GameObject)Instantiate(object_prefab, generator_proxy.transform.position, generator_proxy.transform.rotation);
         new_object.name = (System.Guid.NewGuid().ToString("N")).Substring(0, 6);
    }

    }

Here's AutoDestroy.cs, which is attached to the prefab object_prefab

public class AutoDestroy : MonoBehaviour {

    void OnBecameInvisible()
    {
        Destroy(gameObject);
        Debug.Log(name + " is out!"); // This line prints!
    }

    void Update()
    {
       /// If I put Destroy(gameObject); here, it works!
    }

}

Now I start the game. When new objects go off-screen, Debug.Log(name + " is out!"); fires and works as expected, but Destroy(gameObject); does not fire and nothing happens!

But if I put Destroy(gameObject); in  void Update () it works :\

I also tried :

GameObject get_obj = GameObject.Find(name);
Destroy(get_obj);

No luck! :(

How can I make it work ?


texts: How do you apply relativistic physics to a 4x strategy game?

texts:
I had the big idea of trying to create a hard science fiction 4X strategy game (with the obvious space setting), which is supposed to simulate a realistic way of creating interstellar societies while simulating real life physics as well.

The problem is: how do I apply Einstein's relativistic equations into the game? I will make a separate series of questions for other issues, such as applying Keplerian planetary movement and Newtonian combat physics.

Do note: the game is being made in C++ and in Unity. Be warned: I am trying to simulate special relativity, not general relativity quite yet. That I can try in a different game.


texts: Should I throw out game heavily using OpenGL 2.0 and rewrite it from scratch?

texts:
I've picked up one old open source game (done with C++/Lua) with a lot of features and chosen to continue its development. It use SDL2 (ported by me from 1.2) and OpenGL 2.0. Now when I look at futher development it seems that mobile platforms don't support legacy OpenGL stuff, which is used really heavily: entire arhitecure is based on calling gl functions from lua side, where rendering functions are specified.

I'm not quite a pro in 3D development, so I'm not sure is it easier to change current architecture to modern OpenGL or re-write all the stuff. There are some other architecture problems (not GL related ones).

So, is it better to try changing exsisting architecture or start all from scatch, using modern stuff like OpenGL 3.1+ or Vulcan?


texts: Unity/C# : How to execute a function after another function has finished its execution?

texts:
I've been trying to build a "event system" for a project that I'm working on . Here is how I'm doing it : I populate a list with reference to a gameObject and the functions that I need to execute from that gameObject . Then , when the "event" is triggered (in this case , when the player steps into a trigger collider) I just loop over the list and Invoke the functions inside it.

The problem with this is that every single function inside the list gets executed at the same time. This works fine in some cases but if I want to create a more cinematic event I need to have the ability to execute a function after the previous one has finished it's execution .Sadly I have no idea how to do that.

I've been reading a lot of the documentation of both Unity and C# about coroutines and delegates but I can't seem to wrap my head around all those things and find a way to do implement them on code .So I need your help with that :How can I achieve this?

TL;Dr version : I need your help in coming up with a way to execute a function after the previous function has ended it's execution .These functions would be stored in an array or list.

Here is the code of the trigger of the event itself

public class ActivateEvent : MonoBehaviour {

private bool activated;
public Signal[] actionList;
[HideInInspector]
public int actionEventAmount;

// Use this for initialization
void Start()
{
    activated = false;

}
void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.tag.Equals("Player") && !activated)
    {
        Activate();
    }
}

public void Activate()
{
    activated = true;
    for(int i=0;i<actionEventAmount;i++)
    {
        actionList[i].Invoke();
    }
}

}

and here is the code for the Signal Class

public class Signal
{
   public GameObject target;
   public string method;
   public string argType;

   public Signal()
   {

   }
   public Signal(System.Type argType)
   {
       this.argType = argType.FullName;
   }

 public void Invoke()
    {
        if (target != null && !string.IsNullOrEmpty(method))
            target.SendMessage(method, SendMessageOptions.RequireReceiver);
    }
    public void Invoke(object value)
    {
        if (argType != null)
        {
            if (target != null && !string.IsNullOrEmpty(method))
            {
                if (argType.Equals(value.GetType().FullName))
                    target.SendMessage(method, value, SendMessageOptions.RequireReceiver);
                else
                    Debug.LogError("Incorrect parameter type, expected [" + argType + "], got [" + value.GetType().FullName + "].");
            }
        }
        else
            Invoke();
    }
}

public class SignalAttribute : System.Attribute
{
    public string name;

    public SignalAttribute()
    {

    }
    public SignalAttribute(string name)
    {
        this.name = name;
    }
}


texts: How To Rotate A Vector around A Pivot Point

texts:
In Unity, I'm trying to figure out how to rotate an object around a pivot point.
I found a snippet of code over on the regular stack overflow, but it wasn't working even close to correctly. I have edited it a bit and now its starting to work a little better, but its still pretty off from what I need.
It rotates around the object, but about half way through it jumps to another position. The one half actually rotates with the pivot point, albeit a little bit offset from where it should be, and if you keep rotating it the offset becomes greater and greater. Then the other half is just completely off, still not as bad as the original code though.

Sorry I'm having trouble explaining, here is a GIF to make it easier.

 public Vector3 RotTesta(Vector3 point, Vector3 pivot, Quaternion pointRotation, Quaternion pivotRotation)
        {
            //To rotate an object around an arbitrary point, translate first (the arbitrary offset) then rotate as opposed to rotate-scale - translate

            Vector3 offset = point - pivot;
            Vector3 rotationOffset = pivotRotation.eulerAngles - pointRotation.eulerAngles;
            offset = Quaternion.Euler(rotationOffset) * offset;
            return offset + pivot; // calculate rotated point
        }

This just handles its position, after you call this you would just do transform.rotation = pivotRotation.

If someone could please help me out with this I would be very grateful.


texts:
My models are stored as a set of meshes, each with a vertex list and normal list per key-frame, and indices for GL_TRIANGLES which is shared for all frames.  Each frame I lerp between two adjacent key-frames to generate the vertices for that frame on the CPU and then draw it.

How can I move this into a GLSL vertex shader?  Can a shader interpolate between two sets of vertices, and how can I store those vertices on the GPU?


texts: How to benefit from cpu cache in a entity component system game engine?

texts:
I often read in the ECS game engine documentations that is a good architecture for using cpu cache wisely.

But I can't figure how we can benefit from cpu cache.

If components are saved in an array (or a pool), in contiguous memory, it's a good way to use cpu cache BUT only if we read the components sequentially.

When we use systems, they need entities list which are list of entities that have components with specific types.

But these lists give the components in a random way, not sequentially.

So how to design a ECS to maximize the cache hit ?

EDIT :

By example, a Physic system needs an entities list for entity that has the RigidBody and Transform components (There is a pool for RigidBody and a pool for Transform components).

So its loop for updating entities will be like this :

for (Entity eid in entitiesList) {
    // Get rigid body component
    RigidBody *rigidBody = entityManager.getComponentFromEntity<RigidBody>(eid);

    // Get transform component
    Transform *transform = entityManager.getComponentFromEntity<Transform>(eid);

    // Do something with rigid body and transform component
}

The problem is that the RigidBody component of entity1 can be at the index 2 of its pool and the Tranform component of entity1 at the index 0 of its pool (because some entities can have some components and not the other and because of adding / deleting entities / components randomly).

So even if components are contiguous in memory, they are read randomly and so it will have more cache miss, no ?

Unless there is a way to prefetch the next components in the loop ?


texts: Where does my .sav file default to in XNA 4.0 when using the StorageDevice class?

texts: I am using the StorageDevice class built into XNA and am looking to delete my save file from the solution in my XNA game.  I never specify where the save file is to save, and can't find the default location on MSDN documentation.  I am developing this game for the pc, and never prompt the user to select a save device. Where can I find the save file so that I may delete it?


texts: Game Physics: Calculating a collision response using the Separating Axis Theorem?

texts:
I am working on a project in which I have implemented the Separating Axis Theorem to detect collisions between objects. My current collision response is an object that contains whether it is overlapping and what the minimum translation vector (MTV) is.

I then take the MTV and add it to the linear velocity of the object we're testing. This all works fine. However, I want to add rotational forces to the object based on the collision. For this, I imagine we will need two things:

The Minimum Translation Vector, which represents the force
A contact point, which is the point at which the MTV-force gets applied to the object

However, I have been struggling with calculating the contact point for the past two/three days. I haven't been able to find good resources on this, unfortunately.

How would I go about calculating a suitable collision response as I described? Thank you very much!


texts: Getting a sampler of the default rendertarget (null)

texts:
I've been working on a mod for "Duck Game" that adds dark levels like in Spelunky.

I read this guide on how to make shaders, but in my case I don't have access to the draw method and since the game isnt drawn in a rendertarget first I can't do the same blending as he did.

I wrote my own shader that sets the alpha based on the average color value, looks like this:

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    // TODO: add your pixel shader code here.
    float4 color = tex2D(s0,coords);
    color.a = 1-((color.r + color.b + color.g)/3);
    return color;
}

And it looks like this in game:

I personally isn't satisfied with how this looks but to make it like in the tutorial (which is way better) I would need to get the sampler of the main draw (with current rendercontext set to null).

Is there a way to get the pixels on screen so that I can use it like in the tutorial?
I'll also accept answers with better ways of doing it.


texts:
I'm looking to generate a grid style navigation system in Unity. I have created a map in Tiled and am unsure how to continue considering the tiles will have different properties.

The closest example I can think of  would be something akin to the Fire Emblem series of games, in which sprites navigate across the terrain using square tiles.

Any advice on how to achieve this, preferably without paying for a unity asset, would be greatly appreciated. If it helps, I'm hoping to run this on a mobile device.

Here is an example.


texts:
Zooming an OrtographicCamera effectively changes the amount of world units that can be shown in the camera window. Should thus the camera viewport dimensions be correspondingly updated upon zoom? For example,

...
camera.zoom -= 0.01;
camera.viewportWidth *= camera.zoom;
camera.viewportHeight *= camera.zoom;
camera.update();
...

EDIT: Here's the full code:

private float CAMERA_WIDTH = 50;
private float CAMERA_HEIGHT = 50;
camera = new OrthographicCamera(CAMERA_WIDTH,CAMERA_HEIGHT);
camera.position.set(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2, 0);
camera.update();
// prints 1.0, 50.0, 50.0   --> OK
System.out.println(camera.zoom + ", " + camera.viewportWidth + ", " + camera.viewportHeight);
...

camera.zoom += 0.1;
camera.update();
// prints 1.1, 50.0, 50.0   --> NOT Ok
System.out.println(camera.zoom + ", " + camera.viewportWidth + ", " + camera.viewportHeight);
...

Executive summary: if you need the zoomed camera viewportWidth and viewportHeight, maintain them as separate variables. They must not be changed in the camera otherwise zoom calculation messes up (obviously, since the zoom is relative to the values the camera was created with, so the original values are always needed). If you absolutely want or need to reassign camera.viewportWidth and camera.viewportHeight, you have to reset camera.zoom to 1 immediately after.


texts: How to use mipmap with TextureAtlas and AssetManager

texts:
I searched on the Internet but couldn't find the way to use mipmaps with libGDX TextureAtlas. I want atlas instead of normal textures because as far as I know mipmap supports only 2^n width and height and my single textures have other width and height but atlas have 2048x1024.

I can use mipmaps with Texture using

TextureParameter param = new TextureParameter();
param.minFilter = TextureFilter.Linear;
param.genMipMaps = true;
manager.load("data/mytexture.png", Texture.class, param);

but it's not working with TextureAtlas, I tried to change TextureParameter to TextureAtlasParameter but this class don't have genMipMaps field and can't be passed to load method, too.


texts:
I'm trying to create a third person camera in my XNA game. I'm able to move the model I have and the camera at the same time, although the camera is not "following" the model. The model moves faster than the camera. Ultimately, I want the camera to rotate with the model with the left and right keys, and move the model with forward and back.

This is in my update method

    if (keyState.IsKeyDown(Keys.D))
        {
            camera.Rotation = MathHelper.WrapAngle(camera.Rotation - (rotateScale * elapsed));
        }

        if (keyState.IsKeyDown(Keys.A))
        {
            camera.Rotation = MathHelper.WrapAngle(camera.Rotation + (rotateScale * elapsed));
        }

        if (keyState.IsKeyDown(Keys.W))
        {
            camera.MoveForward(moveScale * elapsed);
            player.Position += new Vector3(0.1f, 0f, 0f);
        }

        if (keyState.IsKeyDown(Keys.S))
        {
            camera.MoveForward(-moveScale * elapsed);
            player.Position += new Vector3(-0.1f, 0f, 0f);
        }

player is the model I'm using. Currently the A and D keys don't do anything with the model.

    public class Camera
{
    private Vector3 position = Vector3.Zero;
    private Vector3 lookAt;
    private Vector3 baseCameraReference = new Vector3(0, 0, 1);

    private bool needViewResync = true;

    private float rotation;

    public Matrix Projection { get; protected set; }
    private Matrix cachedViewMatrix;

    public Vector3 Position
    {
        get
        {
            return position;
        }

        set
        {
            position = value;
            UpdateLookAt();
        }
    }

    public float Rotation
    {
        get
        {
            return rotation;
        }

        set
        {
            rotation = value;
            UpdateLookAt();
        }
    }

    public Matrix View
    {
        get
        {
            if (needViewResync)
                cachedViewMatrix = Matrix.CreateLookAt(Position, lookAt, Vector3.Up);

            return cachedViewMatrix;
        }
    }

    public Camera(Vector3 position, float rotation, float aspectRatio, float nearClip, float farClip)
    {
        Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspectRatio, nearClip, farClip);
        MoveTo(position, rotation);

    }

    private void UpdateLookAt()
    {
        Matrix rotationMatrix = Matrix.CreateRotationY(rotation);

        Vector3 lookAtOffset = Vector3.Transform(baseCameraReference, rotationMatrix);
        lookAt = position + lookAtOffset;
        needViewResync = true;
    }

    private void MoveTo(Vector3 position, float rotation)
    {
        this.position = position;
        this.rotation = rotation;
        UpdateLookAt();
    }

    public Vector3 PreviewMove(float scale)
    {
        Matrix rotate = Matrix.CreateRotationY(rotation);
        Vector3 forward = new Vector3(0, 0, scale);
        forward = Vector3.Transform(forward, rotate);
        return (position + forward);
    }

    public void MoveForward(float scale)
    {
        MoveTo(PreviewMove(scale), rotation);
    }
}

I also want to offset the camera for obvious reason, but changing the values in the variable baseCameraReference doesn't change what I want it to


texts: How do I elegantly teach players how to play?

texts:
I've been thinking about how puzzle platformers teach players how to play.

I like Super Meat Boy, particularly the way in which it teaches you without noticing you are being taught. It kept me excited and engaged. There's satisfaction in figuring out something yourself, even if it's simple and clearly forced by the level design.

Other than a "tutorial level" to teach each new skill or rule, are there other ways? What are the benefits and costs of each?


texts: Why is my stage input processor working on the desktop but not on an Android device?

texts:
In my project, I have a button in my stage with a listener.

The problem is that the listener method changed is fired when running the game in desktop but it is not fired when running the game on an Android device.

Any suggestions?


texts: Behavior after collision using masks overlap

texts:
I'm using masks to make collision detection in a game using pygame. The detection works well, but I have had problems with the behaviour after collision.

In most games, the obstacles are vertical or horizontal, making easy manipulate the velocity of objects moving. So, if the object collide, there is just two options: cancel x component or cancel y component. In this way, the object stop the move only in the normal direction.

But, my obstacles have any shape (not any, just rectangles and triangles) and direction, making things hard.

Basically, I want to cancel the velocity component in the normal direction to obstacle in the collision point.

Some help?

Thanks


texts: Coins are solid objects and I can't collect them

texts:
I am just starting out with Unity following along with this video, and I am stuck at roughly 1 hour and 54 minutes in: https://www.youtube.com/watch?v=pwZpJzpE2lQ
It is worth noting that the video uses Unity 2019.4.4f1 whereas I am using Unity 2020.3.2f1.
My issue is that I cannot get my character to pick up coins and they are currently solid, uncollectable objects. The coins are all set to the Coin layer (layer 9) as per the video.
Here is my code (which I looked over a dozen times to see if there were any differences from the video's code and couldn't find any, hence my confusion). Does anyone know where I went wrong?
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] private Transform groundCheckTransform = null;
    [SerializeField] private LayerMask playerMask;

    private bool jumpKeyWasPressed;
    private float horizontalInput;
    private Rigidbody rigidbodyComponent;

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

    // Update is called once per frame
    void Update()
    {
        // Check if space key is pressed down
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyWasPressed = true;
        }

        horizontalInput = Input.GetAxis("Horizontal");
    }

    // FixedUpdate is called once every physic update
    private void FixedUpdate()
    {
        rigidbodyComponent.velocity = new Vector3(horizontalInput, GetComponent<Rigidbody>().velocity.y, 0);

        if (Physics.OverlapSphere(groundCheckTransform.position, 0.1f, playerMask).Length == 0)
        {
            return;
        }

        if (jumpKeyWasPressed)
        {
            rigidbodyComponent.AddForce(Vector3.up * 7, ForceMode.VelocityChange);
            jumpKeyWasPressed = false;
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.layer == 9)
        {
            Destroy(other.gameObject);
        }
    }
}


texts:
I'm looking into creating a 2D line branch, something for a "lightning effect". I did ask this question before on creating a "lightning effect" (mainly though referring to the process of the glow & after effects the lightning has & to whether it was a good method to use or not);
Methods of Creating a "Lightning" effect in 2D

However i never did get around to getting it working. So i've been trying today to get a seconded attempt going but i'm getting now-were :/.

So to be clear on what i'm trying to-do, in this article posted;
http://drilian.com/2009/02/25/lightning-bolts/

I'm trying to create the line segments seen in the images on the site. I'm confused mainly by this line in the pseudo code;

// Offset the midpoint by a random amount along the normal.
midPoint += Perpendicular(Normalize(endPoint-startPoint))*RandomFloat(-offsetAmount,offsetAmount);

If someone could explain this to me it would be really grateful :).


texts: Having multiple different friction values on a single piece of track?

texts:
I am trying to figure out a good/performant way to give a piece of track multiple values of dynamic friction. A track piece is 10x10 units in Unity and the idea is to puzzle them together to a big track like the tracks in Trackmania. The game itself features no acceleration, except from gravity. To make things more interesting I want to give each track piece at the start of the scene multiple random friction values within a given range.
Currently I achieve this by making each piece of track consisting of 100 little tiles which are 1x1 units and they get a random friction values assigned. This approach works somewhat fine as long as there are less than 30 to 40 track pieces(3000-4000 tiles) but with more than that the fps are dropping really low. As it is a racing type of game I had to set the "Fixed Timestep" in the project settings to 0.001 to get accurate time measurments and this is hurting the performance as well. With a lower timestep the collision detection with all the little tiles is really bad too.
Is there a more elegant and/or performant way to achieve this in within the unity physics system?


texts: How can I change this isometric engine to make it so that you could distinguish between blocks that are on different planes?

texts:
I have been working on an isometric minecraft-esque game engine for a strategy game I plan on making. As you can see, it really needs some sort of shading. It is difficult to distinguish between separate elevations when the camera is facing away from the slope because everything is the same shade. So my question is: can I shade just a specific section of a sprite? All of those blocks are just sprites, so if I shaded the entire image, it would shade the whole block. I am using LWJGL.  Are there any other approaches to take?

Here is a screenshot from the engine:


texts:
So I read in another thread that:

  ...the Xbox is a closed system. Forget any direct TCP/IP interaction, you can only communicate with other consoles present in the Xbox Live! network, and you can't do raw HTTP connections.

This makes me curious as to how an app like Last.fm for Xbox LIVE works.  I would think it would require network communications with Last.fm servers, for user identification and for receiving audio streams.

Any ideas?  Thanks in advance.


texts: Unity difficulty placing text within the reference resolution of the canvas

texts:
I have a TextMeshPro GameObject, which I placed within the Canvas. The canvas is set to Scale with Screen Size and has a reference resolution of 1440x1080.

The TextMeshPro GameObject is anchored to the top-right and its position horizontally is -185 from the anchored point (top-right). And within 1440x1080 resolution it looks like:

But when I make my Display resolution higher or smaller (like for example 1920x1080 as in the image below), the TextMeshPro GameObject goes outside game and ends up in the black area.

I tried changing the position of TextMeshPro GameObject via a script attached to the canvas. I came up with the following formula but it seems wrong.

DisplayResolution.x - (DisplayResolution.X + (ReferenceResolution.X - TextMeshPro.Location.X))

Assuming:

DisplayResolution.X = 1920
ReferenceResolution.X = 1440
TextMeshPro.Location.X = -185

Edit - answer to comments:

Where Starry Backfield is at:

Camera settings:

Canvas Settings:


texts: How do I rotate a cube around an axis, relative to the camera view?

texts:
I want to be able to rotate a cube, either by

dragging vertically to rotate it around the Y-axis, or
dragging horizontally to rotate it around the X-axis.

However, when the camera is rotated 90 degrees or more, these directions become wrong relative to the view screen. How can make rotating ‘up’ always mean ‘up’ relative to the camera view?

Here's a picture explaining the situation:


texts: Compatibility between DirectX 9 and DirectX 10 shaders

texts:
I am a beginner to game development and as I am used to programming in C# I decided to go for XNA. I've been playing around with it for a while and now I am learning the basics of HLSL shaders, I have noticed in the MSDN documentation that there have been some syntax changes in HLSL between DirectX 9 and DirectX 10, for example, the Sampler type

Since I am having some troubles with my desktop pc, I am using my laptop which video card only supports DirectX 9.0c. Then I'm gonna have to write my shaders using the DirectX 9 syntax, right? So I am wondering, will my HLSL shaders written using the DirectX 9 syntax work on a system running DirectX 10 (or higher)?