texts:
I am trying to use a constant buffer in a program using SharpDX.Toolkit. I use the Toolkit because it has nice font support for writing on the screen.

The problem I face is in assigning data to the constant buffer.

In the screen below you may see a debug of my code. When it comes to the Draw event the buffer gets empty (obj:9 is active) and in Geometry Shader all values are 0.0f. On event 76 - GSSetShader the obj:16 is active, which contains the data I want to use, non-zero values. I have no idea why it gets overwritten/cleared. I tried assigning or updating buffer in numerous places in the draw method, but none of them helped. For sure it is not a problem of a slot, as in the debug window both (populated and empty) buffers are in slot 0.

NOTE: this way of loading data to constant buffer worked before I switched to using Toolkit, but then the device was explicitly created with SwapChain. I am not so experienced to tell if it may make any difference.

In my effect file I have defined the buffer as

cbuffer ConstantBuffer : register(b0)
{
    float slideX;
    float sinPi075;
    float cosPi075;
    float scaleK;
}

and in the main program

[StructLayout(LayoutKind.Explicit, Size = 16)]
struct GS_CONSTANT_BUF_DATA
{
    [FieldOffset(0)]
    public float slideX;
    [FieldOffset(4)]
    public float sinPi075;
    [FieldOffset(8)]
    public float cosPi075;
    [FieldOffset(12)]
    public float scaleK;
};

followed by

private SharpDX.Direct3D11.Buffer _constantBuffer;
private GS_CONSTANT_BUF_DATA constData;
private int sizeOfconstData;
private SharpDX.Direct3D11.Device _device;
private void InitializeConstantBuffer()
{
    System.Diagnostics.Debug.WriteLine("InitializeConstantBuffer");
    constData = new GS_CONSTANT_BUF_DATA
    {
        slideX = 0.0f,
        sinPi075 = (float)Math.Sin(Math.PI * 0.75),
        cosPi075 = (float)Math.Cos(Math.PI * 0.75),
        scaleK = 0.003f
    };
    _device = (SharpDX.Direct3D11.Device)GraphicsDevice.MainDevice;
    sizeOfconstData = Utilities.SizeOf<GS_CONSTANT_BUF_DATA>();
    _constantBuffer = new SharpDX.Direct3D11.Buffer(
                                       _device
                                     , sizeOfconstData
                                     , ResourceUsage.Default
                                     , BindFlags.ConstantBuffer
                                     , CpuAccessFlags.None
                                     , ResourceOptionFlags.None
                                     , 0);
    _device.ImmediateContext.GeometryShader.SetConstantBuffer(0, _constantBuffer);
    _device.ImmediateContext.UpdateSubresource(ref constData, _constantBuffer);
}

Draw method in the main program

  protected override void Draw(GameTime gameTime)
    {
 GraphicsDevice.Clear(Color.CornflowerBlue);
 for (int i = 0; i < technique.Passes.Count; ++i)
    {
     _device.ImmediateContext.GeometryShader.SetConstantBuffer(0, _constantBuffer);
    _chartGeometry.Draw(
                        GraphicsDevice
                      , SharpDX.Toolkit.Graphics.PrimitiveType.LineList
                      , technique.Passes[i]);
    }
}

And the Draw method associated with _chartGeometry

 public void Draw(GraphicsDevice graphicsDevice, PrimitiveType primitiveType, EffectPass pass)
    {
        if (pass != null)
            pass.Apply();

        // Setup the Vertex Buffer
        graphicsDevice.SetVertexBuffer(0, vertexBuffer);

        // Setup the Vertex Buffer Input layout
        graphicsDevice.SetVertexInputLayout(InputLayout);

        graphicsDevice.Draw(primitiveType, 4, 0);
    }

I have also tried changing buffer to dynamic, and hence, changing UpdateSubresource to Map/Unmap. The result is the same, see creen below, this time obj:16 (has data) and obj:8 (does not).

and while debuging GeometryShader locals show


texts: Collaborative Diffusion vs. A* for loose armies combat: any clear winner?

texts:
Collaborative Diffusion (CD) takes a lot of the work that A* does and combines (writes) it cheaply for multiple agents to read cheaply. This is because the majority of CD's processing works via a simple CA / diffusion approach that produces a single shared map for every agent to use on a given game update. Agents then perform hill-climbing within that space, which is also very cheap.

The primary downside is that the data structure created by CD must apply for all agents; that is, each agent's subjective view of the environment is identical; A* OTOH needs a path calculation per agent, each frame. In spite of this, the relatively low cost associated with CD would seem to make it, on average, a far more suitable approach than A*, even when we must create unique views for agents (comments / experience on this are welcome).

EDIT Consider the following example using Collaborative Diffusion:

Two armies are on a battlefield, each army emitting a uniform scent. They charge (climb the scent gradient), and as the two lines clash, each agent takes on the first, closest enemy agent on the opposing line. This happens because on each approach step for each unit, it checks whether it's yet adjacent to an enemy; if so it locks on / attacks indiscriminately. This is much freer than specific targeting, which is where A* would seem to be a better choice.

Am I correct in these assumptions? Are there other downsides to CD as opposed to [insert your flavour of] A*, for selecting ANY target between large groups?


texts: How to Stop TextMeshPro Truncate from Removing Next Line? Unity 2020.3.1f1

texts:
In updating from Unity 2019 to 2020, it appears the TextMeshPro (TMP_Text) is behaving differently. The code for TMP stayed the same upon updating Unity, so I presume Unity itself must be doing something differently. Nevertheless, I also updated the TMP package and it did not resolve the issue.
The Issue:
I have two lines of text in one text box. I want the overflow to be truncated, but to keep the second line in existence. Example Input:
This is the really long text on the first line that I want cut but
still have this line show.

In short, I want it to read as follows when using the "truncate" option like it used to work before
This is the really long text
still have this line show.

Instead, the second line disappears and it acts as if I have only that first line (centered vertically).
This is the really long text

So how do I get this functionality back? Is it possible?


texts: Procedural Planets, Heightmaps and Textures

texts:
I am currently working on an OpenGL procedural planet generator.  I hope to use it for a space RPG, that will not allow players to go down to the surface of a planet so I have ignored anything ROAM related.  At the moment I am drawing a cube with VBOs and mapping onto a sphere.

I am familiar with most fractal heightmap generating techniques and have already implemented my own version of midpoint displacement (not that useful in this case I know).

My question is, what is the best way to procedurally generate the heightmap.  I have looked at libnoise which allows me to make tilable heightmaps/textures, but as far as I can see I would need to generate a net like this.

Leaving the tiling obvious.

Could anyone advise me on the best route to take?

Any input would be much appreciated.


texts: problems programmatically creating UIView on iPad App

texts:
I have been struggling with this problem for a few days.

My iPad app is designed to be a portrait game. To satisfy Apple's expection, I also support landscape mode. When it goes into landscape mode, the game goes into a letterbox format with back borders on the sides.

My problem is I am creating the UIWindow and UIView programmatically. For some unkown reason, the touch controls are "locked" in to think I'm always in landscape mode. And even though visually in portrait mode everything looks correct, the top and bottom of the screen does not respond to touch.

To summarize how I am setting this up, let me provide the skeletal framework of what I'm doing:

in main.cpp:

int retVal = UIApplicationMain(argc, argv, nil, @"derbyPoker_ipadAppDelegate");

In the delegate, I am doing this:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
 CGRect screenBounds = [[UIScreen mainScreen] bounds];
 CGFloat scale = [[ UIScreen mainScreen] scale ];

 m_device_width = screenBounds.size.width;
 m_device_height = screenBounds.size.height;
 m_device_scale = scale;        // Everything is built assuming 640x960

 window = [[ UIWindow alloc ] initWithFrame:[[UIScreen mainScreen] bounds]];
 viewController = [ glView new ];
 [self doStateChange:[blitz class]];

 return YES;
}

The last bit of code sets up the UIView...

      - (void) doStateChange: (Class) state{
 viewController.view = [[state alloc] initWithFrame:CGRectMake(0, 0, m_device_width, m_device_height) andManager:self];
 viewController.view.contentMode = UIViewContentModeScaleAspectFit;
 viewController.view.autoresizesSubviews = YES;
 [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

The problem seems to related to the line viewController.view.contentMode = UIViewContentModeScaleAspectFit;

If I remove that line, touch works correctly in portrait mode. But the negative is when I'm landscape mode, the game stretches incorrectly. So That's not a option.

The frustrating thing is, when I originally had this set up with a NIB file, it worked fine. I have read through the docs about UIWindow, UIViewController and UIView and have tried about everything to no avail.

Any help would be greatly appreciated.


texts:
For a game I'm programming I'm looking for a kind of realistic mechanic for simulating the tearing apart of objects. Let me explain:
I have a given point p in a 2-dimensional space (possible later also more dimensions so a solution should be scalable, which i assume is not the problem) and I have a number of forces f1, f2, ..., fn acting on this point p. So normally this point moves over time according to the combination of this forces. But now I'm looking for a kind of realistic mechanic that if forces vary strongly the point/objects gets split up in two points/objects that move in different directions.
Here a simple visual example:

three "similar" forces resulting in one single force (the point will move according to this single vector)

three forces that "tear" the point apart and result in two vectors (point will be split up in two new points that move according two the respective vector)
I amuse we need two give the point some kind of inner force, that defines how easy it is to tear the point apart?
By kind of realistic I mean something that doesn't need to be extremely realistic according to the real world physics but something that would fell kind of real in a video game. So an additional benefit would be that it can be easily computed.


texts: SpriteBatch.Begin() causes everyting else to be drawn incorrectly

texts:
I just added this:

_spriteBatch.Begin();
_spriteBatch.End();

to my app and was greatly confused by the fact that this causes pretty much everything else (all of my 3D objects, that is) to be drawn incorrectly. After the code above has executed, no Z-buffering seems to take place, but instead objects are just drawn in the exace same order as I send them to the scene - with the last object drawn being fully visible even while it is located behing other objects. It also screwes up the sampler state for my textures (which I can fix by setting a new SamplerState for the device).

What is going on and how do I fix it?


texts: Having problems with making a button class (checkIfClick) opengl

texts:
Just basing how sfml does it, I get the globalbound of the object and then check if the mouseposition is within the object. I tried do something like that but I dont know exactly how to do it with opengl. I tried changing the projection from -1 to 1 coords to the size of the application in the hope I could just get the position of the object, but when doing std::cout, it still shows the position in -1 to 1 coords.
So my question is:  "How would I convert my mouseposition to -1 to 1 or vi-versa."
Its actually 0 to 2 and not -1 to 1
So far i have this:
I dont know exactly how to get the top left right with opengl I know with sfml. I would use the position and subtract the half of the width and height to get it but like I said, idk how to do that in opengl. I tried doing that but the object position i still -1 to 1 even though I passed in the
 glm::mat4 proj = glm::ortho(0,width, 0, height,-1,1);

I know my projection is working, because when I enter any big number, my object gets really small.
FYI, just because I see these types of answers alot; I'm not asking you to write me a fully functional button class. I just want a general idea on how it would be done or some article that could help me do that (or a very basic example).
void contain(glm::vec2 position)
{
    if (position.x >= button.left && position.x <= button.right
    && position.y >= button.top && position.y <= button.bottom) {
        std::cout << "True\n";
    }
    else {
        std::cout << "False\n";
    }
}


texts: Placing a circle as close as possible to a specific coordinate without overlapping another circle

texts: I am working on a 2D game in Java. My goal is to place a ball as close as possible to the center without overlapping the balls that are already there. How can this be done?


texts:
I'm making a JS game "Monopoly", where I spawning players in random position inside a rectangle. I need a formula that spawns circles INSIDE a rectangle, without being outside.

Here what I have tried:

randomPosition(left, top, width, height, id) {
    // var x = left + Math.random() * (width-2*this.#playerRadius) + this.#playerRadius;
    // var y = top + Math.random() * (height-2*this.#playerRadius) + this.#playerRadius;
    var x = Math.max(Math.min((left + Math.random() * (width-2*this.#playerRadius) + this.#playerRadius), left+width), left+this.#playerRadius*2);
    var y = Math.max(Math.min((top + Math.random() * (height-2*this.#playerRadius) + this.#playerRadius), top+height), top+this.#playerRadius*2);

    var that = this;
    while(true) {
      var hit = 0;
      for (var i = 0; i < that.playersElements.length; i++) {
          var circle = that.playersElements[i];
          var dx = x - circle.x;
          var dy = y - circle.y;
          var rr = this.#playerRadius + this.#playerRadius;
          if (dx * dx + dy * dy < rr * rr) {
              hit++;
          }
      }
      // new circle doesn't overlap any other, so break
      if (hit == 0 || hit > 200) {
        break;
      } else {
        var x = Math.min((left + Math.random() * (width-2*this.#playerRadius) + this.#playerRadius), left+width)
        var y = Math.min((top + Math.random() * (height-2*this.#playerRadius) + this.#playerRadius), top+height);
      }
    }
    this.playersElements[id] = {
      x:x,
      y:y,
      r:this.#playerRadius,
      id:id
    }
    return [y, x];
  }


texts: Rotate meshes with different pivots, equality

texts:
If I have multiple equal meshes but with different pivots and I make a rotation on the first, is there a way to replicate this rotation to all meshes using a rotation Matrix?
For example, if I have a cube, one with it's pivot in the center and another with the pivot outside of the mesh, how can I rotate the first one 90 degrees on the X axis and use it's rotation Matrix to have the second model rotate on itself and not on his pivot?
Assuming that when I pass on the rotation matrix to other meshes I can't pass the vector of the pivot, is this possible?


texts: Loading different navmeshes at runtime in Unity 5

texts:
In order to improve the extend ability of our maps, we load different components of the map at run time. The idea is a user can use Unity to make a map, drop it into a folder and it will be loaded.

The problem I'm facing is loading in navmeshes at run time. Before Unity 5, it was possible to give a scene a navmesh using Resources.Load and then NavMesh.Instantiate. NavMesh.Instantiate is now gone for whatever reason, and nothing seems to replace it.

Now when trying to use Object.Instantiate with a navmesh asset and instantiating an agent, I get the error "Failed to create agent because there is no valid NavMesh". Is there any known way to set a navmesh at run time anymore?


texts:
Apologies if this is a basic question, or been asked a 1,000 times in the past...

I'm new to Unity, and having problems understanding some of the basics to do with 2D cameras (orthographic), and while I've read a lot nothing has made me have that 'ah-ah!' moment yet.

What I'm trying to create is the following (camera position depicted by the box with the pink dashed line) - where the yellow filled boxes are made up of a whole bunch of sprites.

Overtime, the camera need to move left to right, and then bottom to top...

What my issue seems to be is understanding how I can get the camera to display all of the sprites - in other words, resize the camera view to fit the background sprite's height, and know when to stop the camera in order to start moving it up.

What I'd like to understand is how and why to solve this problem - it's the only way I'll learn!

Thanks

Kieron


texts: Converting Shader to ShaderGraph for URP conversion

texts:
I know there are a bunch of threads asking for help with converting old shaders to ShaderGraph, and this one is no different.
I spent a lot of time trying to get a shader to cast shadows from sprites that also works with transparency. Eventually landing on this thread
I was able to work out the following shader that did what I wanted
Shader "Custom/SpriteShadowWithAlpha"{
    Properties
    {
        [PerRendererData] _MainTex("Texture", 2D) = "white" {}
        _EffectColor1("Effect Color", Color) = (1,1,1,1)
        _Crossfade("Fade", float) = 0
        _FlashColor("Flash Color", Color) = (1,1,1,1)
        _FlashAmount("Flash Amount",Range(0.0,1.0)) = 0
        _Cutoff("Alpha Cutoff", Range(0,1)) = 0.9
        _Color ("Color", Color) = (1,1,1,1)
    [Toggle(_ALPHABLEND_ON)] ALPHABLEND_ON("Enable Dithered Shadows", Float) = 0.0

    }
    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "TransparentCutOut"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend SrcAlpha OneMinusSrcAlpha
        CGPROGRAM
            #pragma surface surf Lambert alpha:blend fullforwardshadows alphatest:_Cutoff
            #pragma target 3.0

            struct Input {
                fixed2 uv_MainTex;
                fixed4 color : COLOR;
            };
            sampler2D _MainTex;
            fixed4 _EffectColor1;
            fixed _Crossfade;
            fixed4 _FlashColor;
            float _FlashAmount;
            void surf(Input IN, inout SurfaceOutput o)
            {
                fixed4 col = tex2D(_MainTex, IN.uv_MainTex);
                fixed4 returnColor = lerp(col, col * _EffectColor1, _Crossfade) * _EffectColor1.a + col * (1.0 - _EffectColor1.a);
                o.Albedo = returnColor.rgb * IN.color.rgb;
                o.Alpha = col.a * IN.color.a;
                o.Albedo = lerp(o.Albedo,_FlashColor.rgb,_FlashAmount);

            }
        ENDCG
    }
    Fallback "Standard"
}

After that I found that using the built-in render pipeline was the difference between 40% and 7% GPU utilization when converted to URP using a different sprite shadow shader.
Problem is the URP shader I found did make sprites cast shadows, but all the lighting was off, and messing with the X rotation on the sprites to get them to stand off the ground would cause them to explode into balls of white light from the directional light....I don't get why.
So I set off to try and convert my old working Shader to ShaderGraph
I have been trying to deduce what parts of this code corelate to what blocks exist in ShaderGraph.
I understand when 2 variables have a * between them I need to use a multiply block
After about 3 hours of linking different blocks I was left with....nothing and a mess

I was wondering if anyone could point me in the right direction as to what blocks correspond to what variables.
Like the code
void surf(Input IN, inout SurfaceOutput o)

I am not too sure what sort of block this would be, it seems like a function, and I have no clue how to make that visually
or the block of "Tags" no idea where to start there
or the toggling of _ALPHABLEND_ON


texts: What makes it hard to protect from hacks/bots in BF3 and Quake Live?

texts:
After playing these games, asking other players/admins, and reading online I am led to believe that Quake Live and Battlefield 3 are frequented by bots and there are plenty of hacks of various kinds. I'm confused how this is possible, or even easy seeing how many players have access to these kinds of "tools" (sic).

Isn't it possible for the game authors to digitally sign the game executables so that when they run, the server can ensure only the allowed client is sending commands, thus preventing any kind of abuse? I.e. every player command would be signed by a private key, or symmetrically encrypted (not sure which would make more sense).

I understand that players can look at the running executable's behavior (memory etc.), but if games are apparently so easy to hack, shouldn't most apps be hacked as well (e.g. Skype, all DRM running on Windows etc.)?


texts: How to use CC photos from Wikimedia properly?

texts:
Here is the situation: I want to create a (perhaps commercial) offline trading card game. Like Magic: The Gathering. My game will be about animals. So I want to use CC photos from Wikimedia as an art for each card.

Photos on Wikimedia are under different CC licenses (CC BY 2.0, CC BY-SA 2.5, CC BY-SA 3.0, CC BY-SA 4.0 and so on). I'm not a lawyer, I just want to try to create a game, so before I start I want to be sure:

Can I use such photos in a commercial product?
How to properly attribute each photo? According to Wiki hints, the usual photo should be attributed in this way:

"By AUTHOR NAME from CITY NAME, COUNTRY NAME - PHOTO CAPTION Uploaded by USERNAME, CC BY 2.0, FILE URL"

It's not enough space on the card for so long text. Can I print a short text on each card (like "Photo by AUTHOR NAME") and also make the web page with full credits for all cards' arts? Or credits should be printed and distributed with each booster?

Thanks in advance!


texts: Changing the sprite position: Modify VBO data or translate it?

texts:
I am beginning with VBO and I want to know if it's better use GL_STATIC_DRAW to make a quad and them translate it, or use DYNAMIC_DRAW and modify the vertex position data directly.

Also when I modify the data of a static VBO the rendering really change!
Why does this happen?
It is supposed to make STATIC object right?


texts: How can I hook into OpenGL initialization on Windows?

texts:
I want hook all OpenGL games/applications. I want load my library only if application actually use OpenGL. Something like Direct3DCreate9 for Direct3D 9 or CreateDXGIFactory for Direct3D 10/11.

I thought this function wglDescribePixelFormat, but some app's/games not use it.


texts: Get GameTime's milliseconds in plain format

texts:
I am trying to fire an action every 125ms.

To get the current milliseconds, I go this way:

double passedMs = GameTime.TotalGameTime.TotalMilliseconds;

//this is a double as well
currentMs += (currentMs - passedMs)

if (currentMs > 125)
{
   //Action
   currentMs = 0;
}

But the value I get in passedMs is not simply milliseconds, it's more like 8833.351.

So what could I do here?


texts: Why do I get an access violation while reading the pixels of an SDL_Surface as follows?

texts:
I'm trying to write a software rasterizer and I'm in the step to texture a triangle. I'm trying to get a pixel from an SDL_Surface which is an image, 100x60 at 24 bits of color depth.

I got a read access violation exception. For instance I try to say

Uint32 * pixels = (Uint32 *)texture->pixels;

then

int pixel = pixels[5900];

It gives an access violation. However the calculated pixels count is correct

int pixel_count  = (texture->pitch / texture->format->BytesPerPixel) * texture->h;

Is this wrong? How can I access the pixels of this surface?


texts: Pathfinding in multi goal, multi agent environment

texts:
I have an environment in which I have multiple agents (a), multiple goals (g) and obstacles (o).

.  .  .  a  o  .  .  .
.  .  .  .  o  .  g  .
.  a  .  .  .  .  .  .
.  .  .  .  o  .  .  .
.  o  o  o  o  .  g  .
.  o  .  .  .  .  .  .
.  o  .  .  .  .  o  .
.  .  .  o  o  o  o  a

What would an appropriate algorithm for pathfinding in this environment?

The only thing I can think of right now, is to Run a separate version of A* for each goal separately, but i don't think that's very efficient.


texts: Game Maker Studio - Check Collision With Subimages

texts:
I have an obj_roulette, which contains 4 subimages, with value 2-5 and image_number 0-3. The value result from roulette stored as var global.roulette.

Then, I make many obj_meteorite, which contains 4 subimages too, spawn from above with random x value and random image_number. Player can shoot them with left-mouse click.

This is what I want:

If image_number obj_roulette is 0, and player shoot obj_meteorite with image_number 0, score +10.
If image_number obj_roulette is 0, and player shoot obj_meteorite with image_number 1, score -10.

I don't know how to check collision between mouse_x/mouse_y and object image_number, and how to match obj_roulette image_number and obj_meteorite image_number.

Is it using collision checking? If it yes, then maybe the example in this link can help:
link 1

Please explain your answer. Thanks.

update

[Simple Diagram Image]

update2

Simple Diagram Image 2


texts: Engaging ways to include party members in a fast-paced action RPG

texts:
Imagine a dynamic action RPG, where you constantly need to use your reflex to avoid bullets and fight against hordes of enemies. What would be a best way to incorporate other team members? I can think of several ways but all have disadvantages:

Giving them orders manually is out of questions when there's so much going around that you need all your attention just to make sure your main is not hit by any incoming attack
Using a dynamic pause like in classic cRPG such as Baldur's Gate makes the game slower and interrupts action that ideally should be quick, dynamic and engaging
Making them autonomous is difficult to balance. If they're too weak or ineffective, then the player will constantly gets annoyed at them, that they can't get anything right and die constantly. If they are too efficient then they can ruin the game because player could just sit back and watch them defeat all the enemies. If they just pretend to engage the enemy to left the action to the player this can happen

Most action RPGs seem aware of these difficulties and prefer to have a single character for the player to run and control. This simplify things greatly but I don't want to lose the party, for plot related purposes, banters, interactions etc. What would be a good way to have the best of both words? How can I best include side characters in a fast and dynamic gameplay?


texts: Getting half plane direction relative from cam position

texts:
Im implementing certain Camera movements in my turn based games. I'm able to place and rotate the camera between two units that attack each other. However it will always move to the same "side". Which isn't necessarily wrong, the rotation of the camera just seems to be sharp when it's on the other side of the half plane ( as of right now it always goes on one half plane). I would like the camera to move to one side relative to the cameras position.

Essentially I just have to flip the Normal which gives me the direction where I have to place my camera:
A and B are units.
C is the current camera position
T is the target position.

Essential code

center =  Vector3.Lerp(attacker.transform.position, target.transform.position, 0.5f);
Vector3 diff = attacker.transform.position - target.transform.position;
Vector3 normal = Vector3.Normalize(diff);
normal = Vector3.Cross(Vector3.up,normal);

//CHECK HALF PLANE HERE
normal *= -1;

//Center is the target position.
center -=  normal * (diff.magnitude + 1.0f);


texts:
I have got some problem implementing bullet physics into my opengl game. The thing is that it doesn't want to update my translatef value continously but only at the end.
The code for bullet looks like this:

void CGL::initPhysics( void ) {
broadphase = new btDbvtBroadphase();
collisionConfiguration = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collisionConfiguration);
solver = new btSequentialImpulseConstraintSolver;
dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher,broadphase,solver,collisionConfiguration);

dynamicsWorld->setGravity(btVector3(0,-10,0));

ballShape = new btSphereShape(1);
pinShape = new btCylinderShape(btVector3(1,1,1));
pinShape->setMargin(0.04);

fallMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,10,0)));
btScalar mass = 1;
btVector3 fallInertia(0,0,0);
ballShape->calculateLocalInertia(mass,fallInertia);

btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0,1,0),1);

btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(0,-1,0)));
btRigidBody::btRigidBodyConstructionInfo groundRigidBodyCI(0,groundMotionState,groundShape,btVector3(0,0,0));
btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
dynamicsWorld->addRigidBody(groundRigidBody);

btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass,fallMotionState,ballShape,fallInertia);
btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
dynamicsWorld->addRigidBody(fallRigidBody);

for (int i=0 ; i<300 ; i++) {
    dynamicsWorld->stepSimulation(1/60.f,10);

    btTransform trans;
    fallRigidBody->getMotionState()->getWorldTransform(trans);

    fallY = trans.getOrigin().getY();
}
state_list.remove( STATE_FALL_BALL );
printf("stoped\n");

}

And the drawing function which is called at the beginning looks like this:

void CGL::fallingBall( void ) {
glPushMatrix();

float colBall2[4] = { 0.0f, 0.0f, 1.0f, 1.0f };
glMaterialfv( GL_FRONT, GL_AMBIENT, colBall2);

glTranslatef(0.0f,fallY,0.0f);

printf("fallY: %f\n",fallY);

glutSolidSphere(1.0f,20,20);

glPopMatrix();

}

The thing is that it shows correct value in this function's printf but translation is called only at the beginning I mean I can only see the last state.

Can anyone help me, please?


texts: Convert a one-player client to a hotseat

texts:
I'm making a card game (inspired by Dominion, Hearthstone, Gwent, and others). The way it's set up now, it has a player manager that handles a player's resources and hand of cards, while I have a game manager that handles anything else. At the moment it is set up so that behind the scenes there really is just one player, while the opponent is actually the game manager moving cards around with no regards for the rules of the game, using information sent over the network to mirror what the real opponent is doing at their computer. (I don't care about cheating. I'm not planning to go big; I just want to be able to play and test the card game itself with friends across the country.)

However, I would also like for there to be a hotseat variation on this game. In other words one that is played by two people on one computer. I don't know if it would work out in practice. Things like the length of turns and how much a player can do during the opponent's turn isn't quite fixed yet (note: allowing the players to keep their hands secret from one another is not a concern at the moment).

How would I implement it easiest? Just have one player manager that "switches sides" and swaps out all its fields once a turn is over? That seems ungainly and prone to errors. A second player manager? That would need quite a bit of rewriting of the game manager, and remember that it should still mainly be used online.


texts: A Simple Method To Create Island Map Mask

texts:
I'm searching for a nice and easy way to generate a mask for an island map with C#.

Basically I'm using with a random heightmap generated with perlin noise, where the terrain is NOT surrounded by water.

The next step would be to generate a mask, to ensure the corners and borders are just water.

Then I can just subtract the mask from the perlin noise image to get an island.

and playing around with the contrast..

and the gradient curve, I can get an island heightmap just like I want it..

(these are just examples of course)

so as you can see, the "edges" of the island are just cut off, which is not a big problem if the colour value is not too white, because I will just divide the grayscale into 4 layers (water, sand, grass and rock).

My question is, how can I generate a good looking mask like in the second image?

UPDATE

I've found this technique, it seems to be a nice starting point for me, but I'm not sure how exectly I can implement it to get the desired output.
http://mrl.nyu.edu/~perlin/experiments/puff/

UPDATE 2

this is my final solution.

I've implemented the makeMask() function inside my normalisation loop like this:

        //normalisation
        for( int i = 0; i < width; i++ ) {
            for( int j = 0; j < height; j++ ) {
                perlinNoise[ i ][ j ] /= totalAmplitude;
                perlinNoise[ i ][ j ] = makeMask( width, height, i, j, perlinNoise[ i ][ j ] );
            }
        }

and this is the final function:

    public static float makeMask( int width, int height, int posX, int posY, float oldValue ) {
        int minVal = ( ( ( height + width ) / 2 ) / 100 * 2 );
        int maxVal = ( ( ( height + width ) / 2 ) / 100 * 10 );
        if( getDistanceToEdge( posX, posY, width, height ) <= minVal ) {
            return 0;
        } else if( getDistanceToEdge( posX, posY, width, height ) >= maxVal ) {
            return oldValue;
        } else {
            float factor = getFactor( getDistanceToEdge( posX, posY, width, height ), minVal, maxVal );
            return oldValue * factor;
        }
    }

    private static float getFactor( int val, int min, int max ) {
        int full = max - min;
        int part = val - min;
        float factor = (float)part / (float)full;
        return factor;
    }

    public static int getDistanceToEdge( int x, int y, int width, int height ) {
        int[] distances = new int[]{ y, x, ( width - x ), ( height - y ) };
        int min = distances[ 0 ];
        foreach( var val in distances ) {
            if( val < min ) {
                min = val;
            }
        }
        return min;
    }

this will give an output like in the image #3.

with a little bit of change in the code, you can get the originally wanted output like in image #2 ->

    public static float makeMask( int width, int height, int posX, int posY, float oldValue ) {
        int minVal = ( ( ( height + width ) / 2 ) / 100 * 2 );
        int maxVal = ( ( ( height + width ) / 2 ) / 100 * 20 );
        if( getDistanceToEdge( posX, posY, width, height ) <= minVal ) {
            return 0;
        } else if( getDistanceToEdge( posX, posY, width, height ) >= maxVal ) {
            return 1;
        } else {
            float factor = getFactor( getDistanceToEdge( posX, posY, width, height ), minVal, maxVal );
            return ( oldValue + oldValue ) * factor;
        }
    }


texts: How relevant is the ability to move/rotate buildings post construction in city builders?

texts:
I am playing with the concept of a city builder and I have seen many around, but I am still fresh in the area of game design.

I have seen city builders where, once you build a building, you have to demolish it to free the space in order to redesign your city. Once you start with a mistake, you have to work around it and in the end you get...ugliness. Improvisation. But its realistic. You have to plan ahead. Maybe restart the game without making that mistake. But this is discouraging to do. I often get frustrated with punishing games and feel no obligation to take the negative impact of my actions.

On other hand you have games that let you reposition / rotate the buildings after you construct them. While this is obviously unrealistic, you don't get punished for your earlier mistakes and have the freedom to aesthetically reshape your city to your liking. Still, you don't require foresight and I feel you are almost robbed of the reward of the foresight. Also, it breaks the immersion somewhat, you feel like "playing a game".

I can't touch on the relevancy of this. It seems such a trivial matter but I can't put my finger on it.


texts:
How can I disable an Animator from the Animation in Unity?
The Animator enablement checkbox seems to be highlighted, which makes me believe that the enablement of the Animator is an animatable property itself. But whenever I try to animate it the enablement toggling just does not get recorded onto the animation line.

It feels like I am missing something here. If someone notices me doing something wrong, could you, please, point it out.


texts:
VERY IMPORTANT NOTE: Im trying to fill a triangle. I have already made the 3D part. Sorry if this wasn't understandable.

I'm currently trying to create a simple 3D-Engine. Well, I have successfully drawn a triangle using this method.

void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
  drawLine(x1, y1, x2, y2); //Usage: drawLine(x, y, x1, y1)
  drawLine(x2, y2, x3, y3);
  drawLine(x3, y3, x1, y1);
}

After this method worked surprisingly well and a cube appeared very convincing, I tried to add lighting. Now I'm facing a pretty big problem. After a long thought I found this method of filling a triangle but here is the problem. It paints a few triangles but not all. Unfortunately I cannot show any pictures because I do not have a camera and a screenshot would not work (as I explain later). My theory is that it only draws bottom flat triangles (or the other way around). What should I change about my method so that it works? Thanks in advance.

This is my filling code:

void FillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
 drawLine(x1, y1, x2, y2);
 drawLine(x2, y2, x3, y3);
 drawLine(x3, y3, x1, y1);
 for(int x = x1; x<=x2; x++) {
    for(int y = y1; y<=y2; y++) {
     drawLine(x3, y3, x, y);
    }
  }
}

I'm currently working with an Arduino UNO
I'm using the Nokia 5110 display
I'm using C++
I'm using this library for displaying
Do not downvote, just comment what you need to know.
I have already tried this code but it wasn't working.


texts:
I know how to create a basic AI for a game, where the AI simple creates units that only march forward. The AI only decides when to create a new unit, taking into account a number of considerations.

But now, I'm working on a game where the user controls a spaceship that can move in any of 8 directions (up, down, left, right, and any of the 4 diagonals).

The user is battling another spaceship that moves in the same way. The spaceships can shoot missiles. The missiles fly in the direction the shooting-spaceship is facing.

I need to program the AI, but have no idea how to make such an AI. Could you give me some general direction on how to make an AI that computes it's movements on the screen?

I have some very general idea, I would also like to know if this is somehow a decent direction:

The AI ship always tries to get inside a specific radius from the user's ship. Once it does, it moves up, down, left, or right to a point where it will be able to hit it's opponent. Then it shoots a missile in the direction of the user's ship.

Is this a decent direction? Any ideas or places where I can get started learning these things? My main concern is how the AI will compute it's movements.\

EDIT: Both the enemy ship and the player's ship can face any direction.

Thanks


texts:
I want to make a game using libGDX game library which should run on android devices. I don't want to use android studio. I want to use eclipse ide.

When I run libgdx-setup.jar, it asks for android sdk's location, but I am unable to find android sdk's download link in the official website.


texts: Find new position of rotated by 10 degrees line

texts:
I have a line that goes to x (x1) of 300, and then I rotate the line by -10 degrees. How can I get the new x (x0) of the rotated line?

Here's a picture to show what I mean:

Are there any books that would help me learn this stuff?


texts: State of the art Culling and Batching techniques in rendering

texts:
I'm currently working with upgrading and restructuring an OpenGL render engine. The engine is used for visualising large scenes of architectural data (buildings with interior), and the amount of objects can become rather large. As is the case with any building, there is a lot of occluded objects within walls, and you naturally only see the objects that are in the same room as you, or the exterior if you are on the outside. This leaves a large number of objects that should be occluded through occlusion culling and frustum culling.

At the same time there is a lot of repetative geometry that can be batched in renderbatches, and also a lot of objects that can be rendered with instanced rendering.

The way I see it, it can be difficult to combine renderbatching and culling in an optimal fashion. If you batch too many objects in the same VBO it's difficult to cull the objects on the CPU in order to skip rendering that batch. At the same time if you skip the culling on the cpu, a lot of objects will be processed by the GPU while they are not visible. If you skip batching copletely in order to more easily cull on the CPU, there will be an unwanted high amount of render calls.

I have done some research into existing techniques and theories as to how these problems are solved in modern graphics, but I have not been able to find any concrete solution. An idea a colleague and me came up with was restricting batches to objects relatively close to eachother e.g all chairs in a room or within a radius of n meeters. This could be simplified and optimized through use of oct-trees.

Does anyone have any pointers to techniques used for scene managment, culling, batching etc in state of the art modern graphics engines?


texts: What is pokemon-like game's view called?

texts:
I'm trying to make a game with a top down view, but angled, like pokemon, zenonia, zelda(I think), and most rpgs(specially the ones made with rpg maker).
But I don't know what is this view called so I'm finding it tricky to get resources or even assets. I heard things like bird-view, 3/4. But I don't really know the exact name.
I would also apreciate any resources or guide with this type of games.

Thanks!


texts: Issues loading in AudioSource at runtime using WWW class

texts:
I am having an issue with loading in an OGG audio file to my project. Basically I want to set my game up so that players can drop audio files into a folder called Playlist in the game directory then they can listen to this music while they play.

For some reason my audio clip never becomes instantiated. I have an Audio Source in my scene with this script attached to it.

As you can see I have commented out some code for the time being as I am trying to get a simple case of only 1 audio file playing at this stage.

So my question is what exactly am I doing wrong here? I have printed out the file path and it comes out as file://B:/Users/Matt/Development/Unity Projects/Space Game/Playlist/19_Tumbling_Dice.ogg which is the location to my audio.

However when I print out the audioLoader.audioClip.name it comes out as blank...

[RequireComponent(typeof(AudioSource))]
public class MP3AudioImporter : MonoBehaviour {

    private List<string> playlist;
    private string musicDir = "B:/Users/Matt/Development/Unity Projects/Space Game/Playlist/";
    private int currIndex = 0;

    void Start()
    {
        string[] songs = Directory.GetFiles(@musicDir, "*.ogg", SearchOption.TopDirectoryOnly);
        playlist = new List<string>(songs);

        StartAudio();
    }

    void StartAudio()
    {
        WWW audioLoader = new WWW("file://" + playlist[currIndex]);

        Debug.Log(audioLoader.audioClip.name);

        audio.clip = audioLoader.audioClip;
        audio.Play();

        /*
        currIndex++;

        if (currIndex > playlist.Count)

            currIndex = 0;
        }

        Invoke("StartAudio", audio.clip.length + 0.5f);
        */
    }
}


texts: How to end the game after the player has defeated all the enemies in Game Maker?

texts:
I'm making a simple version of the game asteroids as I'm learning how to develop with Game Maker Studio. Currently, mostly everything works properly except that when the player destroys all of the asteroids, I need the game to exit.

I've tried add the following line of script to the step event for the asteroid, but it resulted in a runtime error:

if (!instance_exists(obj))
  game_end();

This is a pretty simple problem but I haven't been able to find the answer on Google. What code should I add to check for any instances of asteroids and then to end the game when there are none?


texts:
I've been using Monodevelop's current version and Unity 4.
I don't get intellisense on the classes I've created but I do have intellisense on classes that are in Unity's framework. Bug or its just as it is?

I use UnityScript:

class SomeClass extends ScriptableObject{
    public function Test(){return "";}
}

In another class, when I use a variable typed as this class I get no intellisense.


texts: Accessing soft keyboard on Android via Monogame

texts:
I have a game built in Monogame targeting the Android and iOS platforms. I need to develop a login form for the game. I've begun to roll out my own UI components (text inputs, buttons, so forth), as I've read that there are no commonly used libraries for this purpose.

Now, I'm looking to access on the soft keyboard (for Android at the moment) but can't seem to get it working.

I've looked into the GamerServices module, but I'm pretty sure this only applies to Windows OSes.

I'm trying to implement what looks like the C# wrapper to the Android API. While debugging this code in Visual Studio 2015, the ShowKeyboard function executes without error, but the onscreen keyboard in the emulator doesn't appear.

I've added the following functions to my Android Activity class generated by Monogame, then access these functions when appropriate in-game. The code executes, but alas no keyboard.

    public static void ShowKeyboard()
    {
        var pView = KeyboardConfig.game.Services.GetService<View>();
        var inputMethodManager = KeyboardConfig.Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
        inputMethodManager.ShowSoftInput(pView, ShowFlags.Forced);
        inputMethodManager.ToggleSoftInput(ShowFlags.Forced, HideSoftInputFlags.ImplicitOnly);
    }

    public static void HideKeyboard()
    {
        InputMethodManager inputMethodManager = KeyboardConfig.Application.GetSystemService(Context.InputMethodService) as InputMethodManager;
        inputMethodManager.HideSoftInputFromWindow(KeyboardConfig.pView.WindowToken, HideSoftInputFlags.None);
    }


texts: OpenGL — Better to switch out material or shader for changing object colors?

texts:
I'm fairly new to shaders and OpenGL so bare with me please, I just want to make sure I'm doing it correctly! Now I'm using LibGDX in order to create a simple 3d diagram for my company. I have a few models that I need to display as grey until they are active, where they will fade to a brighter blue, probably gain some emission value so that they're brighter.

Now, when I export my models from Blender to .fbx, and then run Fbx-Conv to generate .g3dj files, I get some output like the following:

"materials": [
    {
        "id": "glowy_blue_material",
        "ambient": [ 0.000000,  0.000000,  0.000000],
        "diffuse": [ 0.000000,  0.753256,  1.000000],
        "emissive": [ 0.000000,  0.753256,  1.000000],
        "opacity":  0.592209,
        "specular": [ 0.000000,  0.759441,  1.000000],
        "shininess":  9.607843,
        "textures": [
            {
                "id": "Texture",
                "filename": "heat_exchange_uv_edge_highlight.png",
                "type": "DIFFUSE"
            }
        ]
    }
]

Which is all good and displays what I want, but I've been reading about shaders the past few days and see that in a lot of cases LibGDX suggests extending the default shader and making tweaks that way.

From a computational point of view, what is the best way to go about switching colors of models? Extending the default shader with some logic about if x is inactive, change shader to render as greyscale, else render as normal blue material? Or should I create a greyscale version of the material and switch them out? ( I'm not quite sure how to do this, also, because I apply the material in the g3dj file — could I do this in Java instead of the g3dj file? Does it cause a performance hit? If anyone could point me in the direction of some documentation somewhere.. )

Any help would be appreciated. Thanks!


texts: How do you create test for unity variables that are set through the [SerializeField] tag?

texts:
I need to create some tests for a bunch of variables that are initialized via the editor, So in the script they are always null and can't be set publicly.

Usually using the tag is a good way to encapsulate the code but with tests how do I check such a variable? Example:

public class thing
{
    [SerializeField]
    private string line;

    //constructor(s), methods, etc..

    public void setLine(string text){line = text; }
}

How do I check the value of the string after it is set inside a test?
(preferably without creating a getter method)


texts: Instanced based game with multiple node instances

texts:
I have a nginx load balancer with 4 nodejs instances behind it, and one Redis server to share certain memory.

My game is an instance game, similar to Diablo 2. Players can create "games" if you will and other players can join them.

The game data is stored locally on the players node of which who created the game (I was going to store the game data in Redis, but have the following dilemma):

When a game is made from a user that is on node instance #1; and a user that is on node instance #2 wants to join that game. This is where I get confused. I want the players to communicate to each other locally (but they cannot because they are not on the same instance). How exactly can I counter this?

These are some solutions I found:

Use ZeroMQ or Nanomsg to send the data locally between processes
Use the native nodejs IPC protocol to send the data locally
between processes

Now, this worries me more. Because I have a feeling I am doing it wrong.  When a player is moving around in the map, he needs to send data to all other 5 players in that game. (simple positional packet).  This now has to be sent through ZeroMQ (pub subbed) -- or through local sockets (IPC). Isn't this going to be a lot of overhead? Are there other ways to scale an instanced based game with multiple node instances? Or maybe, this is the right way, and I'm underestimating how fast local sockets are (or ZeroMQ's speed)?


texts:
I need to make a simulation with stone thrown through a glass window. How can I accomplish that?

I mean, I was thinking about making a 3D model of a stone and glass in 3D Studio Max 2012, shatter the glass and export both to XNA 4.0 as .x models. Then in XNA make the animation - writing my own physics engine. Is it possible that way? Is it possible to destroy the glass in XNA after impact or should I do it in 3DS Max? By 'destroying the glass' I mean disconnect some previously shattered glass bits from each others, because depending on the start-speed and weight of the stone and resistance (hardness?) of the glass (all user-defined) the bits will disconnect from each other in different ways.


texts:
Heyho,

i got problems with my sudoku generator. First of all I generate some numbers between 1 and 9 and put them (according to the sudoku rules) into my game. After that I solve it using my second algorithm, but there's a problem with. It stops solving in the middle of the sudoku and says that there isn't a single solution for it, even if this sudoku has around 200 solutions.

private void generateSudoku()
{
//iSeed für den Random-Generator
iSeed = seeder.Next();
rnd = new Random(iSeed);

for(int i = 0; i < FIELDSIZE; i++)
{
    iContent[i] = 0;
    bEditable[i] = true;
}

switch(iDifficulty)
{
    case 0:  iNumbers = rnd.Next(30, 35);
        break;
    case 1:  iNumbers = rnd.Next(24, 29);
        break;
    case 2:  iNumbers = rnd.Next(18, 23);
        break;
    default: iNumbers = rnd.Next(24, 29);
        break;
}

for(int i = 0; i <= iNumbers; i++)
{
    int iValue = rnd.Next(1, 10);
    int iRow = rnd.Next(0, ROWSIZE);
    int iCol = rnd.Next(0, ROWSIZE);

    if(check(iRow, iCol, iValue) == 0)
    {
        iIndex = (ROWSIZE*iRow+iCol);
        iContent[iIndex] = iValue;
        bEditable[iIndex] = false;
    }else
    {
        i--;
    }
}

iSolutionCounter = 0;
solveSudoku(0);

Console.WriteLine("Solutions: " + iSolutionCounter);

if(iSolutionCounter != 1)
{
    //generateSudoku();
    //return;
}

for(int i = 0; i < FIELDSIZE; i++)
{
    if(bEditable[i] == true)
    {
        iSolution[i] = iContent[i];
        //iContent[i] = 0;
    }else
    {
        iSolution[i] = iContent[i];
    }
}

}

FIELDSIZE = 81;    The number of fields in complete sudoku (9x9)
ROWSIZE = 9;       The number of fields in a single row or column (9)
iNumbers           The amount of random generated startnumbers

And the solveSudoku(), which should solve the sudoku and sum up all solutions (but fails)

private bool solveSudoku(int iPos)
{
    int iCol = (iPos % ROWSIZE);
    int iRow = (int)(iPos / ROWSIZE);

    if(iPos >= FIELDSIZE)
    {
        iSolutionCounter++;
        return false;
    }

    if(iContent[iPos] >= 1)
    {
        return solveSudoku(iPos + 1);
    }
    for(int i = 1; i <= ROWSIZE; i++)
    {
        if(check(iRow, iCol, i) == 0)
        {
            iContent[iPos] = i;
            if(solveSudoku(iPos + 1))
            {
                return true;
            }
        }
    }

    return false;
}

That's what I mean (grey numbers are the ones, which are available at start, so you (or my algorithm) can't edit them:


texts: How can I make an enemy to step around solid objects and follow the player at a given distance?

texts:
var target_distance = 40;
var distance_to_object = 0;

target_distance = distance_to_object(objPlayerParent);

if ( target_distance >= follow_distance )
{
    mp_potential_step_object(objPlayerParent.x, objPlayerParent.y, 1, objEnemyParent);
}

With this code, the enemy ships are chasing the player, but are still colliding with each other, they also rather fly around the player than following his trail.

mp_potential_step(objPlayerParent.x, objPlayerParent.y, 1, true)

This did not lead to the desired effect either.

How can I make an enemy to step around all solid objects in my level and follow the player at the given distance?

More context: The whole game plays in space and at the moment there are not many objects, but each type of object has it's own parent ( objPlayerParent, objEnemyParent, objPowerUpParent etc) and they are supposed to avoid all objects marked as solid. I also apologize for the quite noobish question but I am really new to advanced AI programming.


texts: Web Card Game , MySQL vs SQLite performance wise

texts: Been thinking of creating a js/PHP/MySQL game, with multiple players / games happening concurrently. Is there any chance SQLite might be faster for something like this than MySQL? Keep in mind that I'll propably test this on a shared hosting server...


texts:
Consider a shooter and a target. My question is if there is any realistic approximation of calculating with which probability the shooter hits the target.

Neglecting the weapon and shooter skill, I guess the first order approximation should be that the probability to hit would be proportional to 1/r^2, where r is the distance to the target.

The motivation to this relation comes from using the idea that the area of a sphere centered at the shooter decays as r^2. So, the probability to hit a target should be, in worse case scenario, decaying as 1/r^2.

I've tried Googling some relation for any weapon, but I didn't find any...

Does anyone knows more information about this topic? Is this approximation valid?

EDIT:

More on the question: I'm considering a tactics game. In particular, I would like to model the shooting between two units (so, not a FPS game, the player does not aim, it issue orders). To do that, I'm considering that the unit has some experience, the weapon has some accuracy, and the environment (foggy, vegetation, etc) effects the overall accuracy. Before working some difficult model, the simplest model to test is considering all factors constant, and accuracy only depending on distance.

The question is how does this accuracy should depend on the distance. My first guess would be a 1/r^2 decay. But, has well mentioned on comments, this looks like a very rapid decay.


texts: what function creates rotation effect in three.js?

texts:
which part of the code is responsible for the rotation in this example? Is it the camera or the scene itself?

http://threejs.org/examples/#canvas_camera_orthographic


texts: Faster way to do multi texture blending(HLSL, triplanar texturing and overhang mapping)

texts:
Right now I'm doing a lot of lerping to blend my textures based on height(under water, mid ground and height ground), normal.y >= 0.0 for the under side of the terrain, fractal blend map for a marble effect and then triplanar mapping for the slopes.

It looks good and runs ok and I'm getting just the right blending effect where I need but I'm just thinking that all the lerping could be bad?

I end up with this in my terrain shader:

//Find the blend value for the blend zones
float IsLowGround = saturate(max(distance(min(input.WSPosition.y, 350), 350) / 300, 0));
float IsHeighGround = saturate(max(distance(min(input.WSPosition.y, 1500), 1500) / 1250, 0));

//Find the flip value
float3 flip = saturate(float3(normal.x < 0.0, normal.y >= 0.0, normal.z < 0.0));

//triplanar
float3 blend_weights = max((abs(normal) - 0.2) * 0.5f, 0.0f);
blend_weights = pow(blend_weights,2.0f);
float total = (blend_weights.x + blend_weights.y + blend_weights.z);
blend_weights /= total;
float2 coord1 = float2(input.WSPosition.zy / 750);
float2 coord2 = float2(input.WSPosition.zx / 150);
float2 coord3 = float2(input.WSPosition.xy /700);

//Marble blend maps
float Blend = BlendMap.Sample(colorSampler, input.WSPosition.xz / 2500).r; // flat blend
float Blend2 = BlendMap.Sample(colorSampler, input.WSPosition.zy / 6000).r;   //slope blend

//Color and Normal blending

//Slope Color With Marble
Color += lerp(ColorMap.Sample(colorSampler, coord1) * blend_weights.x, ColorMap6.Sample(colorSampler, coord1 * 3) * blend_weights.x,Blend2);
Color += lerp(ColorMap2.Sample(colorSampler, coord3) * blend_weights.z, ColorMap6.Sample(colorSampler, coord3 * 3) * blend_weights.z, Blend2);

//Slope Normal with marble
NormalM += lerp(NormalMap.Sample(colorSampler, coord1).rgb * blend_weights.x, NormalMap6.Sample(colorSampler, coord1 * 3).rgb * blend_weights.x, Blend2);
NormalM += lerp(NormalMap2.Sample(colorSampler, coord3).rgb * blend_weights.z, NormalMap6.Sample(colorSampler, coord3 * 3).rgb * blend_weights.z, Blend2);

//Height based Color Blending with marble eg. (mid -> height) -> marble
float4 GroundColor = lerp(lerp(ColorMap5.Sample(colorSampler, coord2 / 1.5) * blend_weights.y, ColorMap1.Sample(colorSampler, coord2) * blend_weights.y, IsHeighGround), ColorMap7.Sample(colorSampler, coord2) * blend_weights.y, Blend);

 //Height based Normal Blending with marble eg. (mid -> height) -> marble
float3 GroundNormal = lerp(lerp(NormalMap5.Sample(colorSampler, coord2 / 1.5).rgb * blend_weights.y, NormalMap1.Sample(colorSampler, coord2).rgb * blend_weights.y, IsHeighGround), NormalMap7.Sample(colorSampler, coord2).rgb * blend_weights.y, Blend);

 //Last Color Blending with underside flip eg. (underwater -> Ground) -> flip
Color += lerp(ColorMap4.Sample(colorSampler, coord2 / 2) * blend_weights.y, lerp(GroundColor, ColorMap3.Sample(colorSampler, coord2 * 1.2) * blend_weights.y, IsLowGround), flip.y);

 //Last Normal Blending with underside flip eg. (underwater -> Ground) -> flip
NormalM += lerp(NormalMap4.Sample(colorSampler, coord2 / 2).rgb * blend_weights.y, lerp(GroundNormal, NormalMap3.Sample(colorSampler, coord2 * 1.2).rgb * blend_weights.y, IsLowGround), flip.y);

Here is what it looks like when rendered:


texts: Life Counter in Greenfoot caught "Incompatible Types" exception

texts:
I need to make a life counter so that when my Actor get hit by an Enemy, his life will be decreased by 1.

I put this method in my Actor class:

private void decreaseLife() {
    Actor enemy = getOneIntersectingObject(Enemy.class);
    if (enemy != null) {
        int lastIndex = Scenario.getLifeBar().size()-1;
        Life LastLife = Scenario.getLifeBar().get(lastIndex);
        /** catch error on lastIndex --> "incompatible types" **/

        getWorld().removeObject(enemy);

        getWorld().removeObject(LastLife);
        Scenario.getLifeBar().remove(lastIndex);
    }
}

I used Scenario.getLifeBar().size() - 1; to get the last index from my ArrayList collection then decrease it by 1. My LifeMax was set to 3, so when decreased by 1 it should be returning value = 2, and be saved in lastIndex.

This is my code including LifeBar code in Scenario Class:

import greenfoot.*;
import java.util.ArrayList;

public class Scenario extends World {
    private final int LIFE_MAX = 3; //Max value of my Actor's life
    private static ArrayList LifeBar = new ArrayList();

    public Scenario() {
        super(600, 400, 1);
        prepare();}

    private void prepare() {
        prepareLifeBar(40, 30);
        // Add obj. main actor
        // Add obj.enemy
    }

    private void prepareLifeBar(int offsetX, int offsetY) {
        int spaceBetweenLife = 10;  // just to put space between image
        for (int i = 0; i < LIFE_MAX; i++) {
            Life life = new Life();
            life.setLocationX(offsetX+((life.getImage().getWidth()+spaceBetweenLife)*i) );
            nyawa.setLocatinY(offsetY);
            addObject(life, life.getLocationX(), life.getLocationY());
            LifeBar.add(life);
        }
    }

    public static ArrayList getLifeBar() {
        return LifeBar;
    }
}

In my Life class, I put some code to add attributes of LocationX and LocationY to save my Life actor in x and y axis.

I believe there's no other exception caught in any other class related to my life counter, yet my lastIndex caught an incompatible types exception.

What's causing this exception to be thrown?


texts: What are the pros and cons of a non-fixed-interval update loop?

texts:
I am studying various approaches to implementing a game loop, and I have found this article.

In the article, the author implements a loop which, if the processing falls behind in time, skips frame renderings and just updates the game in a loop (the last variant called "Constant Game Speed independent of Variable FPS").

I do not understand why it is acceptable to call update_game() in a loop without making sure the update function is called at a particular interval. I do not see any value in doing this. I would think that, in my game, I would want to be sure that the game is updated periodically with a known period.

Maybe it is worthwhile to have two threads, where one would call the update function, periodically, and the other one would redraw the game, also periodically. Of course, I would need to synchronise the threads. Would this be a good and practical approach?


texts: Working with websockets in Unity: Cannot convert lambda expression to type 'IObserver' because it is not a delegate type

texts:
I'm a bit stuck on a delegate error in Unity. The code works fine if I'm in a c# console app however Unity is giving me the error:

Cannot convert lambda expression to type 'IObserver' because it is not a delegate type.

client.ReconnectionHappened.Subscribe(type =>
            {
                Log.Information($"Reconnection happened, type: {type}, url: {client.Url}");
            });

I tried updating to the latest Unity for the c# 8 support but that didn't appear to fix anything. I'm guessing it has something to do with .net compatibility and Unity. Do I need to create this delegate some other way to be compatible with unity?
I've been looking at the code here.
Websockets Server for Unity3d
Using this for the client
https://github.com/Marfusios/websocket-client


texts: Libgdx switching between screens without losing Information

texts:
I've been having issues with Screens, as I want to switch between the main game screen, the battle screen and the ingame menu screen (JRPG). The problem is that I have initialised all the information (Position of Player and NPC's, Map data, Sava data, etc) in the Show() function of the screen. That means that when I switch between 2, it will rebuild and reload everything all over again. There is also no Create() function in Screen so I'm at a dead end right now. Is there a way I can reserve data or draw the other screen on top of the main game screen, pausing that one?

I really need help with this.


texts: How do I apply pixel shader to specific sprite in XNA 4.0 in a spritesort FrontToBack?

texts:
I have a set of sprite drawn in FrontToBack sortmode. In XNA 4.0, the effect must be as an input argument of Begin() function of SpriteBatch. However, If I reinvoke the function, then the sprite sorting is lost. Therefore, I have to find a way to implement the pixel shader within the Begin() and End() for specific texture drawn. I tried to use effect.CurrentTechnique.Passes[0].Apply(), but no pixel was shaded when I invoke this. On the other hand, if I put effect as an argument, then all of the sprites would be effected. Therefore, is there any convenient way to approach this?

By the way, what I am trying to do is to provide an overlay on an isometric tile using some kind of masking. Therefore, I want to draw such masking and programmatically change it to optional color.

Something like this (from final fantasy tactics):

I am not sure if pixel shader is the right way to approach it, but then I have to tackle the fact that I want to be able to specify optional color dynamically. Other than that, I really want it to animate, which I might approach this by creating several grayscale animated masking and saturate it using pixel shader.


texts: Unity2D: Rendering multiple sprites as a single one

texts:
I'm creating NPCs in Unity 2D using C#, and I have 16x16 sprites for body, helmet, clothes and weapon. All these have a tile set which has been split in unity. I'd like to be able to render one of each part together, so I can drag the sprite to the field, and then it will be rendered on the NPC. IE, I drag a helmet sprite into the helmet field and that is the rendered helmet.

I intend on having multiple NPCs, so I'd prefer to minimise the child objects. Multiple sprites will need rendering, however there's only one sprite renderer. Is it possible for me to combine the sprites (in code), and then render the final sprite? Or is there perhaps a better way?

Thanks in advance!


texts: Why was 24-bit color support introduced twice in GPUs?

texts:
I was doing research, trying to answer the question "Which was the first GPU to support 24-bit color". I know all color since 1992 is 24-bit, even in games like Doom. I mean 16 million simultaneous colors on the screen, not just 256 unique colors from a 24-bit palette.
I started digging, and naturally I came across the ATI Mach 32. Later I find out that RIVA TNT also "added" support for truecolor. So I'm left wondering, is 24-bit color support some ancient technology that was forgotten after 1992 and rediscovered in the year 1998? Or are they talking about something different?
I have two guesses, but I'd love to know the real explanation:

Truecolor support in RIVA TNT meant it's hardware accelerated, as in the sprites are stored in the VRAM, as opposed to the Mach 32, where the VRAM is just a frame buffer so acceleration would be considered software.
Nvidia meant 32-bit color texture, not even talking about frame buffer pixel depth.

Anyone know what both Nvidia and ATI really meant?


texts:
I hope someone knows how to do the following with cocos2d:

I want a sprite to move but not in a single line by using

[cocosGuy runAction: [CCMoveTo actionWithDuration:1 position:location]];

What I want is the sprite to do some kind of movements that I preestablish. For example in some point i want the sprirte to move for instance up and then down but in a curve. Do I have to do this with flash like this documents says?

http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:animation

Does animation in this page means moving sprites or what?

thanks


texts:
I am continuing my previous question( link ). Now its working as per this demo.

and the coding written to set cutoff is here :

function Update () {

    renderer.material.SetFloat("_Cutoff", Mathf.InverseLerp(0, Screen.width, Input.mousePosition.x));

}

But i want to set cutoff value , depending up on distance between two object.

one object position will be static. and i am moving another object and if my object gets far distance then cutoff should be 0. and if the object gets closer then depending up on the distance between these two object , i want to set cutoff value.

so how do i set cutoff value?

Please help me guys?

Thanks in advance for your support and help in advance.


texts: Choosing between Playmaker or Game Creator for a non-coder

texts:
The Unity Asset Store is having a huge sale today and saw these two featured.
I'm trying to create a one-level third-person horde mode shooter. It would spawn in at least 3 different enemy types that I can shoot at in a set amount of waves. I would like to know which one can easily make this for me as a non-coder. AI doesn't need to be that extensive just monsters chasing after the Player is enough.
Not to say too much, I just need this much to green light something so I would like to hear your advise
Thanks!


texts: Converting motionevent.getx and motionevent.gety to pixel or Object coordinates in the view

texts: I am trying to draw buttons using OpenGL I have added a Gesture Listener for the GLSurface View now i have motionevent when ever the user touches. My question is how can i convert motionevent.getx and motionevent.gety (which are in pixel range )to window or Object coordinates of the view?


texts: Algorithm to generate small tree-like branches?

texts:
I'd like to seed a void map with "branches" of sine waves or any other waveform. Something like:

Know of any algorithm? Has to be one to generate trees or something like that.


texts:
Someone told me that the movement concept in my 2D game is bad. When left or right arrow is pressed I'm scrolling the background which makes you feel that player avatar is moving (the avatar's X-position remains the same).

So... he told me something about matrix view. I should create all walls and platforms static and scroll only the camera and move the player's rectangle. I did a little research in Google, but found nothing.

Can you tell me anything about it? How to start? Maybe links, books and resources?


texts: What makes a shader function with a LineRenderer?

texts:
A LineRenderer has both Material and Color properties.
But many shaders do not work, ie the line will not respect the Color property, or the line will show black (regardless of the materials having its own color).

For example the Standard, Diffuse, Mobile/Diffuse shaders all show black.  Unlit/Color ignores the LineRenderer color and uses only the Material Color property.  Particles>Additive works great, but Particles>Standard Surface does not.

What part of the shader code is important to make a LineRenderer display using its own Color property?  When it does work, how should shader code decide how to merge between the two colors?


texts: How do you do tile-based movement in Phaser?

texts:
I'm looking to make 2D game that is very similar in movement to Pokemon Red or Blue (player must move a full tile in any direction, the ground moves smoothly beneath the player as they walk). I've got my hands on Tiled in order to make my maps, and I've got a player sprite that I can display over the map, but I can't seem to find a way to restrict the player to moving the way I want.

I feel like there should be some parameter for Arcade physics to make the movement the way I want, but I'm not finding it. Abandoning Arcade physics and manually changing the X/Y of the player with a loop kinda works, but can be very slow and laggy, making me think I'd need to look into the Time and Tween parts of Phaser to actually implement it correctly.

So did I miss something with Arcade Physics to do this? Or do I need a really good tutorial on Tween to manually code this myself?


texts: Cannot create EAttachmentRule variable in a Blueprint struct

texts:
I'm trying to add a EAttachmentRule variable in a struct but the enum doesn't appear in the list of available types

I managed to create a variable in a BP by dragging the pin from an AttachActorToComponent node and promoting it to a variable. But I can't do the same thing to create a variable in a struct


texts: SetIKHintPosition and SetIKHintPositionWeight seems to have no impact

texts:
I have recently been exploring Unity's inverse kinematics, to further polish the interaction between our rigged avatars and props.

I have made a sample project, using PuppetMaster's basic humanoid for the model, rig, and idle animation, but without Final IK; meaning this is Unity's inverse kinematics.  Inside our OnAnimatorIK method, we set the right elbow's SetIKHintPosition and SetIKHintPositionWeight like we did with the hand IK:

animator.SetIKHintPosition(avatarIKHint, hintPosition);
animator.SetIKHintPositionWeight(avatarIKHint, hintBlendValue);

animator.SetIKPosition(sourceIKGoal, targetPosition);
animator.SetIKPositionWeight(sourceIKGoal, blendValue);

You can see the left and right hand correctly move to where we set it.  However, it seems like the right elbow is ignoring the hint position entirely.  You can see the white debug line connecting the elbow to the hint position in the picture above.

It seems like the elbow ONLY bends if it absolutely must for the hand to reach the target position, regardless of where the hint is set, and the weight value given.

I have fiddled with this on and off for days and still haven't found a solution.  Others have asked the same question here and on other sites, but no one has posted an answer.


texts: Initializing OpenFeint for Android outside the main Application

texts:
I am trying to create a generic C++ bridge to use OpenFeint with Cocos2d-x, which is supposed to be just "add and run" but I am finding problems.

OpenFeint is very exquisite when initializing, it requires a Context parameter that MUST be the main Application, in the onCreate method, never the constructor. Also, the main Apps name must be edited into the manifest. I am trying to fix this. So far I have tried to create a new Application that calls my Application to test if just the type is needed, but you do really need the main Android application. I also tried using a handler for a static initialization but I found pretty much the same problem.

Has anybody been able to do it? This is my working-but-not-as-intended code snippet

public class DerpHurr extends Application{

@Override
public void onCreate() {
    super.onCreate();
    initializeOpenFeint("TestApp", "edthedthedthedth", "aeyaetyet", "65462");
}

public void initializeOpenFeint(String appname, String key, String secret, String id){
    Map<String, Object> options = new HashMap<String, Object>();
    options.put(OpenFeintSettings.SettingCloudStorageCompressionStrategy, OpenFeintSettings.CloudStorageCompressionStrategyDefault);
    OpenFeintSettings settings = new OpenFeintSettings(appname, key, secret, id, options);

//RIGHT HERE
    OpenFeint.initialize(***this***, settings, new OpenFeintDelegate() { });
    System.out.println("OpenFeint Started");
}

}

Manifest

<application
    android:debuggable="true"
    android:label="@string/app_name"
    android:name=".DerpHurr">


texts: Screen Capture rendered on a RenderTexture in Unity

texts:
I have a pretty wild idea for a unity application that would work on a multi-display setup.

The app would be running in full screen mode on one of my displays, and the contents of the remaining two displays should be rendered in-game on a texture.

I've seen RTMP clients for unity and I've tried streaming my desktop with OBS to a local RTMP server but the delay was too big (more than 5 seconds). I would prefer an instant (or very low delay) solution for mirroring my displays on textures in Unity.

If anyone can help me solve this, i would appreciate it!


texts: How do i get the X,Y and Z of the way my unit is facing?

texts: I have the yaw and pitch of my unit at my disposal, I know if I use polar to cartesian conversion I'll get the X and Y of each one of those two, but I need them combined to give me the x,y and z of the direction I'm facing.


texts: CrossPlatformInput Prefabs - Button handler to move?

texts:
I am currently trying to put two buttons on my UI that move a character left and right if touched down (Held). I would like to use the cross platform input, and would like the buttons to change the value of the Horizontal axis as my "A" and "D" keys would...

And my code for moving my character is as follows:

private void Update()
    {
        isGrounded = Physics2D.OverlapCircle(groundChecker.position, .15f, groundLayer);

        float move = CrossPlatformInputManager.GetAxis("Horizontal") * moveSpeed;
        playerRB.velocity = new Vector2(move, playerRB.velocity.y);

    }


texts: How to render decoded video that is on GPU memory without copying to CPU

texts:
I'm reading this example of ffmpeg hardware decoding: https://github.com/FFmpeg/FFmpeg/blob/release/4.2/doc/examples/hw_decode.c

At line 109 it does this:

/* retrieve data from GPU to CPU */
            if ((ret = av_hwframe_transfer_data(sw_frame, frame, 0)) < 0) {

which means that decoded video is in GPU. Since I want to render this video using Open GL, I guess it's much more efficient to not get this back to CPU but to actually render directly from GPU memory.

Is it possible to render directly from GPU memory?

What I know is that, in order to render from CPU memory, we usually send data from CPU using gltextImage2D function and the shaders will render it. If I want to pass data that is already on GPU, how do I do?


texts: Static evaluation function for Checkers using Minimax

texts:
I have correctly implemented Minimax for my checkers AI till depth of 3 ( well at least that is what I think ). However I am confused on evaluating my game boards at depth 3 with heuristics. Currently I just check ( no of blacks - no of reds ) for my heuristics but then it gives duplicate values ( Tie Breaker ) for most of the game boards. I researched and found that in that case we can assign values to each position on the game board ( found on this link here here  and add it to the heuristic. But how is it implemented exactly and how are those board values chosen? And do I have to apply it for each of my recursion or just at the top level for all the branch nodes?

here is my code.

    int MaxMove(TreeNode currNode, int depth, List<TreeNode> pathNodes)
    {
        if (depth == 0)
        {
            return StaticEvaluationFunction(currNode,depth);
        }
        else
        {
            depth--;
            int v = -10000;
            List<TreeNode> allPossRedMoveNodes = gameBoardScript.createNewRedBoardsFromCurrent(currNode.getCurrentBoard());
            TreeNode bestNode = null;
            foreach (TreeNode RedNode in allPossRedMoveNodes)
            {
                int v1 = MinMove(RedNode, depth, pathNodes);
                if (v1 > v)
                {
                    v = v1;
                    bestNode = RedNode;
                }
                //if the heuristic is equal then add the board piece values to the current heuristic ( I AM NOT SURE IF THIS IS CORRECT )
                else if( v1 == v)
                {
                    v1 += RedNode.getBoardMove().getMovedToPiece().getTieBreakerValue();
                    v = v1;
                }
            }
            return v;
        }
    }

    int MinMove(TreeNode currNode, int depth, List<TreeNode> pathNodes)
    {
        if (depth == 0)
        {
            return StaticEvaluationFunction(currNode, depth);
        }
        else
        {
            depth--;
            int v = 10000;
            List<TreeNode> allPossBlackMoveNodes = gameBoardScript.createNewBlackBoardsFromCurrent(currNode.getCurrentBoard());
            TreeNode bestNode = null;
            foreach (TreeNode BlackNode in allPossBlackMoveNodes)
            {
                int v1 = MaxMove(BlackNode, depth,pathNodes);
                if (v1 < v)
                {
                    v = v1;
                    bestNode = BlackNode;
                }
                //when priorities are equal
                else if (v1 == v)
                {
                    v1 += BlackNode.getBoardMove().getMovedToPiece().getTieBreakerValue();
                    v = v1;
                }
            }
            return v;
        }
    }

    private int StaticEvaluationFunction(TreeNode node, int depth)
    {
        return node.getHeuristic(); // Black - Red count at the last depth
    }


texts: UGUI scripts stop my project from building

texts:
Unity 2019.2.21

I am trying to build out my project to Android and I am getting the following error messages:

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\Toggle.cs(121,18): error CS0234: The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\DefaultControls.cs(152,13): error CS0103: The name 'Undo' does not exist in the current context

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\GraphicRebuildTracker.cs(24,32): error CS0117: 'CanvasRenderer' does not contain a definition for 'onRequestRebuild'

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\EventSystem\InputModules\StandaloneInputModule.cs(159,25): error CS0234: The type or namespace name 'EditorApplication' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\Slider.cs(380,18): error CS0234: The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\Scrollbar.cs(168,18): error CS0234: The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\Selectable.cs(771,48): error CS0234: The type or namespace name 'SceneManagement' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

H:\unity versions\2019.2.21f1\Editor\Data\Resources\PackageManager\BuiltInPackages\com.unity.ugui\Runtime\UI\Core\InputField.cs(2458,43): error CS0234: The type or namespace name 'PrefabUtility' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)

I tried updating Unity(from 2019.2.12 to current).
Deleting some csproj files, and different settings in the Project settings/Player.
The problematic code is in an #if UNITY_EDITOR statement, and not meant to execute at all on builds, I guess.

#if UNITY_EDITOR
        protected override void OnValidate()
        {
            base.OnValidate();

            if (!UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this) && !Application.isPlaying)
                CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
        }

#endif // if UNITY_EDITOR


texts:
People that understand client-side prediction and client-side interpolation, I have a question:

When I play the game Team Fortress 2, and type cl_predict 1 into the developer's console, it enables client-side prediction. The also says "6 predictable entities reinitialized". It says this regardless of how many players are on the server, which makes sense, because other players are not predictable entities.

I thought client-side prediction was only for the movement of the player. Are there other entities that the client can provide prediction for?


texts:
When A computer is to draw a 3d model, does it use maths similar to vector projection? Like when a 3d model is drawn and rotated, does it use vectors/and maybe some other math to know where to draw each of the edges?

If so, is this calculation made everytime the screen is refreshed?

Just want to see if I can create a basic square that looks like its spinning in 3D space. Just for the challenge, not anything practical.

Sorry if I wasn't clear, it is one of those questions where it's difficult to explain.


texts: Raycasting from an object to the center of the screen (crosshair) without clipping through objects

texts:
Am trying to learn about Raycasting, and I thought I would start with something simple, and that was a laser that would come out of an object (think laser pointer in your hand) and always go to the crosshair.

Using ViewportToWorldPoint I found it easy to cast a ray from the center of the camera, but this had an issue as you can see in this GIF below.

The line would clip through because the ray was coming from the center, not off to the side where the laser pointer would be.

Am not sure how to solve this.

void Update(){
    Vector3 ray = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0f));

    line.SetPosition(0, transform.position);

    RaycastHit hit;

    if(Physics.Raycast(ray, Camera.main.transform.forward, out hit, raylength)){
        if(hit.collider != null){
            line.SetPosition(1, hit.point);
        }
    } else {
        Vector3 pos = line.GetPosition(0);
        line.SetPosition(1, ray + (Camera.main.transform.forward * raylength));
    }
}

The closest thing I could find that I am trying to replicate for this exercise is the No Man's Sky mining tool


texts:
I've been reading up on these, and there seem to be two major variations which I'd like to understand better.

Entities should contain only data Components, which are processed by systems which contain the logic
Entities can contain data and behaviour components

What are the benefits of one over the other? Which scenario would be appropriate for which approach?

What about the other variations, such as message handeling entities/components?

For example, say I want to attach a certain AI behaviour to an entity, approach #2 would let me do that intuitively by simply adding it to the behaviours of the entity. With approach #1, I'm not sure how it would be done, possibly by attaching a data member specifying which AI to use?

Wouldn't the AI processing system turn into one big switch(AI) { case AI_XYZ : AI_XYZ(); ...}, as opposed to simply calling entity.AI(), or sending a message to the entity that tells it to update the AI...?

As with many things, there doesn't seem to be one "right" way to do this, trying them all doesn't seem feasible, I think most of the dis-/advantages wouldn't become apparent without implementing a sizable number of components and/or systems.

Personally, the message handling kind of components look appealing in a game context, simply being able to grab an entity and telling it to react to something, but I have no experience using such a system.  I hope this question isn't too vague


texts: Storing Type/Game Data Within A Unity 3D Game Using An Offline Flatfile Database

texts:
I've read several documents on how to manage game type data:

Would it be better to use XML/JSON/Text or a database to store game content?

How to choose how to store data?

Im developing an offline RPG game in Unity3D. I've made online games before, but with online we had an edge for the database. For the online game we used a MySQL database each time the player loaded the game, they would download the database (JSON setup) and we would parse it on the client side and it would be good to go.

However for an offline RPG I don't have the luxury of storing my game type data online. To be clear when I say type data I mean things like:
-Monster tables
-Item tables
-Ability tables
etc

What I liked about the MySQL database was that it was tabluar and I could edit rows and columns easily and not need to create hundreds of classes/subclasses to manage the type data.

My question is how can I mimic the MySQL database in Unity3D?

I considered using an excel file but I feel that would be so easy for the user to hack. Just change the excel data and boom, you've hacked the game.

Is there a way I can create an offline (secure-ish) flatfile database that will let me avoid having to create tons of type data class files to manage all my game data?


texts:
I'm currently trying to move my weapon with the camera. To do this i'm creating a vector (tempVect) where i load how much the camera has moved compared to the weapon (in the code behind is just filled with random values to test it). TempTranslation is the XMMATRIX where the translation is stored. result is the XMMATRIX that comes out from the multiplication of tempMatrix and tempTranslation. mPistolWorld is an XMFLOAT4X4 that is going to be loaded into the "world" variable to make the world * view * proj matrix. Now that i have result how can i load it into mPistolWorld ?

XMVECTOR tempVect = XMVectorSet(0.2f, 0.2f, 0.2f, 0);

    tempTranslation = XMMatrixTranslationFromVector(tempVect);

    XMMATRIX tempMatrix = XMLoadFloat4x4(&mPistolWorld);

    XMMATRIX result = XMMatrixMultiply(tempMatrix, tempTranslation);


texts:
I am currently trying around with automatically generating a dungeon.
I'd like to use this tileset https://opengameart.org/content/a-blocky-dungeon
TLDR: how do I automatically apply a texture to a tile on the grid.
The grid consists of void, floor and wall tiles for now. In order for the walls to look good, I spaced out the rooms enough so there is at least one void tile between two wall tiles.
I can't find a decent solution for the double-height walls. There are so many possible outcomes for these pillars.. for example the original tileset does not include "tee" tiles as you can see in my messed up image below.
The only question I found was this one How do you handle uneven tiles while rendering a tile map?
I am currently drawing the wall tile texture as a 16x32 texture, anchored at the bottom.
Do I need to generate every upper wall of a room as a 2 high wall?
My way of assigning the texture to a tile is quite ugly, I have a huge json like this:
"w:wall,e:wall,s:void,n:floor": {
    "x": 6,
    "y": 3
},
...

Is there a standard way of assigning a tileset to a grid? bitmasking doesn't seem to be right here


texts:
I want to be able to draw all my text, lines , triangles and other stuff to screen and then clear the screen and draw something new, BUT this method makes the screen flicker, and all the drawings dont appear at the same time.

My idea is to draw to some kind of a buffer and then draw that buffer to the screen and clear the buffer, and repeat. This way the screen wont flicker and all will be drawn at the same time.

I am using windows.h , Visual Studio.

#include <Windows.h>
#include <iostream>
using namespace std;

struct vec2d
{
    int x, y;
};

void Line(HDC dc, vec2d a, vec2d b)
{
    MoveToEx(dc, a.x, a.y, NULL);
    LineTo(dc, b.x, b.y);
}

vec2d GetMousePos(HWND console)
{
    vec2d out;
    POINT p;
    GetCursorPos(&p);
    out.x = p.x; out.y = p.y;
    return out;
}

int main()
{
    HWND console = GetConsoleWindow();
    HDC dc = GetDC(console);
    SelectObject(dc, CreatePen(PS_SOLID, 1, RGB(255, 255, 255)));

    while (1)
    {
        //BitBlt(dc, 0, 0, 1000, 1000, 0, 0, 0, BLACKNESS);        Flickering is much much bigger, because its faster
        system("cls");
        Line(dc, { 0, 0 }, GetMousePos(console));
    }
}

Thanks in advance, Mark.


texts: Why the random positions are not random?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[ExecuteAlways]

public class GenerateCurvedLines : MonoBehaviour
{
    public GameObject linesPointsPrefab;
    public GameObject linesParent;
    [Range(3, 100)]
    public int numberOfLines;
    [Range(5, 50)]
    public int gap;
    public bool randomLinesPositions;
    public bool generateLines;
    public bool clearPositions;

    private List<Vector3> randomPositions = new List<Vector3>();
    private GameObject instance;

    // Start is called before the first frame update
    void Start()
    {
        if (randomLinesPositions)
        {
            for (int i = 0; i < numberOfLines; i++)
            {
                randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));
            }
        }

        GenerateLines();
    }

    // Update is called once per frame
    void Update()
    {
        if (clearPositions)
        {
            var lr = GetComponent<LineRenderer>();
            lr.positionCount = 0;

            clearPositions = false;
        }

        if (generateLines)
        {
            GenerateLines();

            generateLines = false;
        }
    }

    private void GenerateLines()
    {
        for (int i = 0; i < numberOfLines; i++)
        {
            randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));

            if (randomLinesPositions)
            {
                instance = Instantiate(
                      linesPointsPrefab,
                      randomPositions[i],
                      Quaternion.identity
                   );
            }
            else
            {
                instance = Instantiate(
                      linesPointsPrefab,
                      Vector3.right * gap * i,
                      Quaternion.identity
                   );
            }

            instance.transform.parent = linesParent.transform;
        }
    }
}

At this part I'm trying to Instantiate random positions of the prefabs but each time I check true the flag generateLines it's Instantiating the prefabs at the same positions instead each time to Instantiate them in a new random positions. It's like it's Instantiate once random positions and then using this positions each time and not Instantiating new random positions.
randomPositions.Add(new Vector3(UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50), UnityEngine.Random.Range(5, 50)));

                if (randomLinesPositions)
                {
                    instance = Instantiate(
                          linesPointsPrefab,
                          randomPositions[i],
                          Quaternion.identity
                       );
                }


texts:
I'd like to know what others do to watch for changes in object states while the game is running.

Say you have an object and that object has a timer. The timer completes. What is the best way to know that the timer has completed?

something like?
- add all timers to a vector.
- set a bool when the timer completes
- loop over the vector continuously or at a short interval and watch for the bools?

Seems simple, but is it really that simple? What is the best way to loop over the vector continuously? C++11 thread and detach it from the main?


texts: Bullet spread changes depending on the camera direction

texts:
I'm working on an FPS game. I want to make a little bit of difference in shooting direction, only on the horizontal axis.

To do this, I wrote this code:

Temp_Shake_Horizontal.x = Random.Range(-0.1f, 0.1f);

if (Physics.Raycast(the_camera.position, the_camera.forward + Temp_Shake_Horizontal, out BulletDecal_Hit, Mathf.Infinity))
{
     Quaternion HitRot = Quaternion.FromToRotation(Vector3.forward, BulletDecal_Hit.normal);
     decals_Objs[decal_Index].transform.position = BulletDecal_Hit.point;
     decals_Objs[decal_Index].transform.rotation = HitRot;
}

But I don't know why, when I rotate the camera, the result is changing!

Here is what it looks like when I face in one direction (this is the intended result):

But when I rotate the camera about 90 degrees to the left or right, the result is no horizontal variation: the bullets all line up in a vertical column.

Why does this happen, and how can I solve this issue? I want the result to always be like the first picture, with random variation side-to-side.


texts: How can I reduce the size of a png in unity while maintaining picture quality

texts:
I'm new to Unity.  I'm using Unity 2019.1.3f1 Personal.

My issue is that I have created pictures (png) of a character in Photoshop.  The picture borders look clean in Photoshop and looks okay, not the best, when pasted into Unity.  However, the original picture size is too big but when I make it smaller, the picture quality suffers.

I understand that I can make the picture smaller in Photoshop but is that the most efficient way?  If not, how can I resize pictures in Unity and maintain the picture quality?

Below is a side-by-side comparison of the picture after I resize it (left) and before I resize it (right).  Any suggestions is greatly appreciated; thank you for your time,