My code is:  public void move() {     moveX();     moveY(); }  public void moveX() {     if(xMove &gt; 0) {         int tx = (int) (x + xMove + bounds.x + bounds.width) / Tile.TILEWIDTH;          if(!collisionWithTile(tx, (int) (y + bounds.y) / Tile.TILEHEIGHT) &amp;&amp; !collisionWithTile(tx, (int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)) {             x += xMove;         }     } else if(xMove &lt; 0) {         int tx = (int) (x + xMove + bounds.x) / Tile.TILEWIDTH;          if(!collisionWithTile(tx, (int) (y + bounds.y) / Tile.TILEHEIGHT) &amp;&amp; !collisionWithTile(tx, (int) (y + bounds.y + bounds.height) / Tile.TILEHEIGHT)) {             x += xMove;         }       }  }  public void moveY() {     if(yMove &lt; 0) {         int ty = (int) (y + yMove + bounds.y + bounds.height) / Tile.TILEHEIGHT;          if(!collisionWithTile((int) (x + bounds.x) / Tile.TILEHEIGHT, ty) &amp;&amp; !collisionWithTile((int) (x + bounds.x + bounds.width) / Tile.TILEWIDTH, ty)) {             y += yMove;         }     }      if(yMove &gt; 0) {         int ty = (int) (y + yMove + bounds.y) / Tile.TILEHEIGHT;          if(!collisionWithTile((int) (x + bounds.x) / Tile.TILEHEIGHT, ty) &amp;&amp; !collisionWithTile((int) (x + bounds.x + bounds.width) / Tile.TILEWIDTH, ty)) {             y += yMove;         }     } }  protected boolean collisionWithTile(int x, int y) {     return room.getTile(x, y).isSolid(); }   but when I run it I get a NullPointerException with this StackTrace:  Exception in thread "Thread-0" java.lang.NullPointerException     at com.pixelandbitgames.entities.creature.Creature.collisionWithTile(Creature.java:69)     at com.pixelandbitgames.entities.creature.Creature.moveX(Creature.java:41)     at com.pixelandbitgames.entities.creature.Creature.move(Creature.java:27)     at com.pixelandbitgames.entities.creature.Player.tick(Player.java:19)     at com.pixelandbitgames.states.GameState.tick(GameState.java:23)     at com.pixelandbitgames.game.Game.tick(Game.java:72)     at com.pixelandbitgames.game.Game.run(Game.java:113)     at java.lang.Thread.run(Thread.java:748) I do not see where this is coming from as collisionWithTile has all its parameters filled. If anyone can help me that would be appriciated. if anyone needs any thing else to help I will deliver. My other classes seem fine and it is just this one. This happens when I try to move. my code for Room.getTile is here:  public Tile getTile(int x, int y) {     if(x &lt; 0 || y &lt; 0 || x &gt;= width || y &gt;= height)         return Tile.floorTile;     Tile t = Tile.tiles[tiles[x][y]];     if(t == null)         return Tile.floorTile;     return t; }   and this has no way to return null. Is solid is just a return true unless it is overridden.  public boolean isSolid() {     return false; }
129
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them?  What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?
117357
In C#, what is the difference (if any) between these two lines of code?  tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);   and  tmrMain.Elapsed += tmrMain_Tick;   Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?
67839
I implemented my game-loop as described in , using the last approach with an unlimited FPS and a constant game-speed.  My problem is, that the unlimited FPS cranks up my CPU usage to nearly 100%. I understand that this is desired (as the hardware does as much as it can), but for my game, it's not really necessary (it's pretty simple). So I'd like to limit the FPS to some upper bound.  Consider my game-loop:  private static final int UPDATES_PER_SECOND = 25; private static final int WAIT_TICKS = 1000 / UPDATES_PER_SECOND; private static final int MAX_FRAMESKIP = 5;  long next_update = System.currentTimeMillis(); int frames_skipped; float interpolation;  // Start the loop: while (isRunning){     // Update game:     frames_skipped = 0;     while (System.currentTimeMillis() &gt; next_update             &amp;&amp; frames_skipped &lt; MAX_FRAMESKIP){         // Update input, move objects, do collision detection...         // Schedule next update:         next_update += WAIT_TICKS;         frames_skipped++;     }     // Calculate interpolation for smooth animation between states:     interpolation = ((float)(System.currentTimeMillis() + WAIT_TICKS - next_update)) / ((float)WAIT_TICKS);     // Render-events:     repaint(interpolation); }   How would I implement a maximum FPS?  If i implement the repaint the way I implemented the update (or use a sleep instead of "do-nothing-cycles"), then the FPS is locked, right? That is not what I want. I want the game to be able to work with lower FPS (just as it does now), but limit the FPS to a maximum of, say 250.
57681
I am developing a small 2D game engine. The characters have a paint method which currently does the following:   Calculate the new position of the character as per its speed, etc. Update the collision grid cell ** Draw the character at the new position   ** I have created a collision grid to reduce the number of intersection checks  Now the basic algorithm which I have thought for detecting collision is:   For Each Character     Check intersection with characters in surrounding 8 cells   I can simply place this code in the paint method. But here is the problem I anticipate.  Suppose two characters A and B lie in adjacent cells in the collision grid. Now as per the above algorithm in the iteration of character A it will detect that it has collided with B. In the iteration for character B it will detect that it has collided with A.  But I have an idea that when A detects that it has collided with B, it should inform B that it has collided with A. This would save lot of comparisons when there are more than 2 actors colliding. But I am not sure how to handle this. I think instead of every character checking for its collision, I should check for the collision inside the game loop.   Would this approach be correct? How have you handled this kind of problem? I thought of the collision grid thing myself. Are there any alternatives to collision grid logic?
62585
Given the following example, why do I have to explicitly use the statement b-&gt;A::DoSomething() rather than just b-&gt;DoSomething()?  Shouldn't the compiler's overload resolution figure out which method I'm talking about?  I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)  class A {   public:     int DoSomething() {return 0;}; };  class B : public A {   public:     int DoSomething(int x) {return 1;}; };  int main() {   B* b = new B();   b-&gt;A::DoSomething();    //Why this?   //b-&gt;DoSomething();    //Why not this? (Gives compiler error.)   delete b;   return 0; }
50289
I'm writing an isometric 2D game and I'm having difficulty figuring precisely on which tile the cursor is. Here's a drawing:    where xs and ys are screen coordinates (pixels), xt and yt are tile coordinates, W and H are tile width and tile height in pixels, respectively. My notation for coordinates is (y, x) which may be confusing, sorry about that.  The best I could figure out so far is this:  int xtemp = xs / (W / 2); int ytemp = ys / (H / 2); int xt = (xs - ys) / 2; int yt = ytemp + xt;   This seems almost correct but is giving me a very imprecise result, making it hard to select certain tiles, or sometimes it selects a tile next to the one I'm trying to click on. I don't understand why and I'd like if someone could help me understand the logic behind this.  Thanks!
85236
Here is my complete code sample   global class b1 implements Database.Batchable&lt;sObject&gt; {   global final string query;  global final string s_object;  global final string field;  global final string field_value;   global b1 (string q, string s, string f, string v){        Query =q;        s_object=s;        field = f;       field_value =v;    }    global Database.QueryLocator start (Database.BatchableContext BC){   return Database.getQueryLocator (query);   }    global void excute(Database.BatchableContext BC, List&lt;sObject&gt; batch) {   for(s_object o= batch){   o.put(field,field_valu);    }   update batch;   }     global void finish(Database.BatchableContext BC){    } }
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
54872
I'm generating a level, and I have an optional delay to show the steps level generation one by one.  If my generationDelay boolean is true, I want to use StartCoroutine to spread the generation out over time. If it's false, I want to call the same method but without StartCoroutine.  The problem is that the method is type IEnumerator.  I can make two methods one type of IEnumerator and one not. But I wonder if there is a way to use one method.  In the first script top i did:  public bool generationDelay = false;   Then in a method:  private void BeginGame()     {         mazeInstance = Instantiate(mazePrefab) as Maze;          if (generationDelay == true)         {             StartCoroutine(mazeInstance.Generate(generationDelay));         }         else         {             mazeInstance.Generate(generationDelay);         }     }   Then the other script where the method Generate is: In the top:  public float generationStepDelay = 0.01f;   Then the method Generate:  public IEnumerator Generate (bool generationDelay) {          if (generationDelay == true)             WaitForSeconds delay = new WaitForSeconds(generationStepDelay);         cells = new MazeCell[size.x, size.z];         List&lt;MazeCell&gt; activeCells = new List&lt;MazeCell&gt;();         DoFirstGenerationStep(activeCells);         while (activeCells.Count &gt; 0) {             yield return delay;             DoNextGenerationStep(activeCells);         }     }   I'm getting an error on the line:   WaitForSeconds delay = new WaitForSeconds(generationStepDelay);      "Embedded statement cannot be a declaration or labeled statement"   And an error on the line:  yield return delay;      "The name 'delay' does not exist in the current context"   The reason I want to use a bool variable is that when i'm using StartCoroutine it's kind of slow, even if I change the value of generationStepDelay to 0 it's kind of slow. And if I'm not using StartCoroutine and not using the Generate method as IEnumerator it will work fast.  So i wonder what should I do and how?
118553
In C++ I can't use a method if I declare it after the calling method.    Does this order matter in other languages like Java or C#?
102091
I am attempting to make a top down game similar to the SNES Zelda games, in Unity 4.3, in 2D. When my character swings their sword, every enemy within a radius takes damage. I want to make sure that melee attacks only damage enemies the player is facing.  How can I do this?    The relevant code in PlayerAttack.cs looks like this:  // Update is called once per frame void Update () {     // have the player initiate an attack on the object     if(Input.GetKeyUp(KeyCode.F)){         MeleeAttack();     } }  private void MeleeAttack(){     // create a variable called distance to make sure the distance is close enough     // to inflict damage from a melee attack target.transform.positon = the position     // of the object to attack and transform.position is the position of the players     // transform     float distance = Vector3.Distance(target.transform.position, transform.position);      // make sure the distance is not greater than 1.5 so the player cannot     // melee an enemy from to far away     if(distance &lt; 1.5f){             // get a reference to the enemy's health script and type cast it.             EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");             // now call the function that will decrease the enemy's health             eh.AdjustCurrentHealth(-10);     } }
16473
Consider the class below that represents a Broker:  public class Broker {     public string Name = string.Empty;     public int Weight = 0;      public Broker(string n, int w)     {         this.Name = n;         this.Weight = w;     } }   I'd like to randomly select a Broker from an array, taking into account their weights.  What do you think of the code below?  class Program     {         private static Random _rnd = new Random();          public static Broker GetBroker(List&lt;Broker&gt; brokers, int totalWeight)         {             // totalWeight is the sum of all brokers' weight              int randomNumber = _rnd.Next(0, totalWeight);              Broker selectedBroker = null;             foreach (Broker broker in brokers)             {                 if (randomNumber &lt;= broker.Weight)                 {                     selectedBroker = broker;                     break;                 }                  randomNumber = randomNumber - broker.Weight;             }              return selectedBroker;         }           static void Main(string[] args)         {             List&lt;Broker&gt; brokers = new List&lt;Broker&gt;();             brokers.Add(new Broker("A", 10));             brokers.Add(new Broker("B", 20));             brokers.Add(new Broker("C", 20));             brokers.Add(new Broker("D", 10));              // total the weigth             int totalWeight = 0;             foreach (Broker broker in brokers)             {                 totalWeight += broker.Weight;             }              while (true)             {                 Dictionary&lt;string, int&gt; result = new Dictionary&lt;string, int&gt;();                  Broker selectedBroker = null;                  for (int i = 0; i &lt; 1000; i++)                 {                     selectedBroker = GetBroker(brokers, totalWeight);                     if (selectedBroker != null)                     {                         if (result.ContainsKey(selectedBroker.Name))                         {                             result[selectedBroker.Name] = result[selectedBroker.Name] + 1;                         }                         else                         {                             result.Add(selectedBroker.Name, 1);                         }                     }                 }                   Console.WriteLine("A\t\t" + result["A"]);                 Console.WriteLine("B\t\t" + result["B"]);                 Console.WriteLine("C\t\t" + result["C"]);                 Console.WriteLine("D\t\t" + result["D"]);                  result.Clear();                 Console.WriteLine();                 Console.ReadLine();             }         }     }   I'm not so confident. When I run this, Broker A always gets more hits than Broker D, and they have the same weight.  Is there a more accurate algorithm?  Thanks!
114020
Second Update: I see that some answers that reference my image are more closely answering my question. Here is a second image to clarify my point.  Take this image representing a checkerboard like configuration.  If I asked you to move the X negative 1 space it would be impossible.  You would have to make a guess as to which direction is negative. However, I can ask you to move the X 1 space/unit, since moving to any square from the center would satisfy moving 1 space/unit.  But wait!  Once you complete moving the X 1 space/unit; I could now follow up and request you move negative 1 space, since you have now already travelled in one direction. Now you are able to negate the original request by 1 space/unit  Therefore negative doesn't exists until you have already begun moving in some direction/unit/space/time/apples.      update   Maybe this helps illustrate my point.  In this image there is a line, going either direction will take you to infinity (A or B),  the number of spaces you move is always a positive number. If I moved 20 widgets closer to infinity A. or I moved 20 widgets closer to infinity B.  So, negative numbers don't exist and are only positive numbers that are increasing in the opposite direction  Negative indicates the direction of travel on a line.  the measure of movements will always be positive.  Does a negative number really exist?  I can't have -1 apples.  I can only imagine I had an apple when I really did not.  Thus, in reality I would have -1 apple as compared to my imagination.  didn't know how to tag this
100547
I'm trying to get the bounds of an object and put a box around it.  Sounds simple right? I just encapsulate all the bounds together and use its center and size to do so.  But the problem is one corner of the box is always at the center of the scene, like a part of the object is there, unless the center of the scene is in the bounds.  This is when object is at the center   This is when it isn't  This is the code i'm using:      public static Bounds Calculate(Transform TheObject)     {         Renderer renderer = TheObject.GetComponent&lt;Renderer&gt;();         Bounds combinedBounds = new Bounds();         if (renderer != null)             combinedBounds = renderer.bounds;         var renderers = TheObject.GetComponentsInChildren&lt;Renderer&gt;();         foreach (Renderer render in renderers)         {             if (render != renderer) combinedBounds.Encapsulate(render.bounds);         }         return combinedBounds;     }
81715
Edit:  Of course my real code doesn't look exactly like this. I tried to write semi-pseudo code to make it more clear of whay I wanted to do.  Looks like it just messed things up instead.  So, what I actually would like to do is this:  Method&lt;Interface1&gt;(); Method&lt;Interface2&gt;(); Method&lt;Interface3&gt;(); ...   Well ... I thought that maybe I could turn it into a loop using reflection. So the question is: How how do I do it. I have very shallow knowledge of reflection. So code examples would be great.  The scenario looks like this:  public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() {     Assembly assembly = Assembly.GetExecutingAssembly();      var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;      foreach(var i in interfaces)     {         Method&lt;i&gt;(); // Get compile error here!     }       Original post:  Hi!  I'm trying to loop through all interfaces in a namespace and send them as arguments to a generic method like this:  public void Method&lt;T&gt;() where T : class {} public void AnotherMethod() {     Assembly assembly = Assembly.GetExecutingAssembly();      var interfaces = from i in assembly.GetTypes()     where i.Namespace == "MyNamespace.Interface" // only interfaces stored here     select i;      foreach(var interface in interfaces)     {         Method&lt;interface&gt;(); // Get compile error here!     } }   The error I get is "Type name expected, but local variable name found". If I try  ...     foreach(var interface in interfaces)     {         Method&lt;interface.MakeGenericType()&gt;(); // Still get compile error here!     } }   I get "Cannot apply operator '&lt;' to operands of type 'method group' and 'System.Type'" Any idea on how to get around this problem?
99218
I currently have something like:  float deltaX = point0.getX() - point1.getX(); float deltaY = point0.getY() - point1.getY();   And every 0.01 seconds I refresh my objects position like this:  object.setPosition(object.getX()-deltaX/100,object.getY()-deltaY/100);   So this moves my object from point0 to point1 in 1 second. What I need is having the 2 points, to be able to move the object from point0 ,facing(in the direction of) point1 with a constant speed. Thus, when I have a point closer to my initial point the object will move towards it with the same speed it does if I would have a farther point. Any suggestions are appreciated. Thanks.
76186
Once it is compiled, is there a difference between:  delegate { x = 0; }   and  () =&gt; { x = 0 }   ?