I try make timers without thread.sleep to stop lag so any ideas how to make this code without thread.sleep but it stop 20ms. Thanks for help! :) And sorry my bad english.
Timer BulletTimer = new Timer();
BulletTimer.Tick += (s, args) => BulletKillPlayer(Bullet);
BulletTimer.Interval = 20;
BulletTimer.Start();
private void BulletKillPlayer(Bullet)
{
bool pX, pY, pD1, pD2, nX, nY, nD1, nD2;
pX = false; pY = false; pD1 = false; pD2 = false; nX = false; nY = false;
for (int i = 1; i < 20; i++)
{
if (User.Range >= i)
{
Thread.Sleep(20);
foreach (MapItem MapItem in MapItem.Boxs.Values)
{
if (MapItem.X == Bullet.X && MapItem.Y == Bullet.Y + i && !pX) { pX = BreakBox(Bullet, MapItem); KillPlayer(Bullet, MapItem); }
if (MapItem.X == Bullet.X && MapItem.Y == Bullet.Y - i && !pY) { pY = BreakBox(Bullet, MapItem); KillPlayer(Bullet, MapItem); }
if (MapItem.X == Bullet.X + i && MapItem.Y == Bullet.Y && !nX) { nX = BreakBox(Bullet, MapItem); KillPlayer(Bullet, MapItem); }
if (MapItem.X == Bullet.X - i && MapItem.Y == Bullet.Y && !nY) { nY = BreakBox(Bullet, MapItem); KillPlayer(Bullet, MapItem); }
}
}
}
}
Related
I have searched the similar games on forum and google but i could not find exactly.
I am making a puzzle game. and user can get point if the nodes (horizontal sticks) are same color then he can get.
when they are in same direction it says colors matched but in generated node whenever i rotate the sticks it says also same.
Can you take a look? and tell me how to fix. Also if you have better idea about this matching I will be appreciated.
---------
void Update()
{
if (Input.GetMouseButtonDown(0))
{
clickTime = Time.time;
rayhit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, selectableObjLayerMask);
}
else if (Input.GetMouseButtonUp(0))
{
if (rayhit)
{
if (Time.time - clickTime < .2f)
{
Node node = rayhit.transform.GetComponent<Node>();
if (node != null)
{
for (int i = 0; i < node.sticks.Count; i++)
{
Vector3 newAngles = new Vector3(0, 0, (node.sticks[i].transform.localEulerAngles.z - 45));
newAngles.z = newAngles.z < 0 ? newAngles.z + 180 : newAngles.z;
newAngles.z = newAngles.z >180 ? newAngles.z - 180 : newAngles.z;
node.sticks[i].transform.localEulerAngles = newAngles;
node.sticks[i].degree = (int)newAngles.z;
//******** HERE IS COLOR MATCHING*******
if (node.transform.parent.name=="Node1" && node.sticks[i].degree == 90)
{
colorMatch[1] = node.sticks[i].color;
Debug.Log("COLOR 1___"+ colorMatch[1]);
//Debug.Log(colorMatch1);
}
if (node.transform.parent.name == "Node2" && node.sticks[i].degree == 90)
{
colorMatch[2] = node.sticks[i].color;
Debug.Log("COLOR 2___" + colorMatch[2]);
}
if (node.transform.parent.name == "Node3" && node.sticks[i].degree == 90)
{
colorMatch[3] = node.sticks[i].color;
Debug.Log("COLOR 3___" + colorMatch[3]);
//if (colorMatch[1] == colorMatch[2] && colorMatch[2] == colorMatch[3])
//{
// Debug.Log("COLORS MATCHED : " + colorMatch[1]);
//}
}
if (colorMatch[1]==colorMatch[2] && colorMatch[2]==colorMatch[3])
{
Debug.Log("COLOR MATCHED");
}
}
}
}
else
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode.isMoved == false)
{
smallestId = 0;
smallestDistance = 999;
for (int i = 0; i < nodes.Length; i++)
{
float distance = Vector2.Distance(rayhit.transform.position, nodes[i].transform.position);
if (smallestDistance > distance)
{
smallestDistance = distance;
smallestId = i;
}
}
rayhit.transform.position = nodes[smallestId].transform.position;
if (rayhit.transform.parent != nodes[smallestId].transform)
{
if (nodes[smallestId].transform.childCount > 0 && nodes[smallestId].transform != rayhit.transform.parent)
{
if (currNode != null)
{
for (int i = 0; i < currNode.sticks.Count; i++)
{
nodes[smallestId].transform.GetChild(0).GetComponent<Node>().sticks.Add(currNode.sticks[i]);
currNode.sticks[i].transform.SetParent(nodes[smallestId].transform.GetChild(0));
}
Destroy(rayhit.transform.gameObject);
}
}
else
{
if (currNode != null)
{
currNode.isMoved = true;
}
rayhit.transform.SetParent(nodes[smallestId].transform);
}
}
}
}
}
rayhit = new RaycastHit2D();
}
else if (Input.GetMouseButton(0))
{
if(rayhit.transform != null)
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode != null)
if (currNode.isMoved == false)
{
if (Time.time - clickTime >= 0.2f)
{
Vector2 newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rayhit.transform.position = newPos;
}
}
}
}
}
if (node.transform.parent.name=="Node1" && node.sticks[i].degree == 90)
{
colorMatch[1] = node.sticks[i].color;
Debug.Log("COLOR 1___"+ colorMatch[1]);
//Debug.Log(colorMatch1);
}
if (node.transform.parent.name == "Node2" && node.sticks[i].degree == 90)
{
colorMatch[2] = node.sticks[i].color;
Debug.Log("COLOR 2___" + colorMatch[2]);
}
if (node.transform.parent.name == "Node3" && node.sticks[i].degree == 90)
{
colorMatch[3] = node.sticks[i].color;
Debug.Log("COLOR 3___" + colorMatch[3]);
if (colorMatch[1] == colorMatch[2] && colorMatch[2] == colorMatch[3])
{
Debug.Log("COLORS MATCHED : " + colorMatch[1]);
}
}
Here is working code. but how i can destroy the matched sticks?
I'm trying to use Yield so my functions wait to spawn more enemies in scene if the max amount has been reached. But now the functions skips all this while cycle in its entirety.
I have never use yield so maybe I'm understanding wrong what it does while reading the documentation.
Also maybe there is a better way to do it.
while ( i < clonesASpawnear.Length)
{
if (j <= endList)
{
if (clonesASpawnear[i] == null)
{
if (sPCurrent == sPMax)
{
sPCurrent = 0;
}
yield return new WaitUntil(() => aliveEnemies < maxAmmoutOfEnemiesOnStage);
clonesASpawnear[i] = Instantiate(enemyTypeList[j], spawnPoints[sPCurrent].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
clonesASpawnear[i].SetActive(true);
clonesASpawnear[i].GetComponent<EnemyMovement_DCH>().player = Target;
aliveEnemies += 1;
clonesASpawnear[i].GetComponent<EnemyDamageHandler_DCH>().SpawnerEnemies = this;
j++;
i++;
sPCurrent++;
}
}
else
{
j = startList;
}
}
}
Edited as requested: here is the update where the function is called
void Update()
{
if (pdh.playerIsDead == false && roundOver==false)
{
playerAliveTime += Time.deltaTime;
}
if (waveNumer <= 3 )
{
timeForNextSpawn -= Time.deltaTime;
if (timeForNextSpawn <= 0 && aliveEnemies == 0)
{
nextWaveTextUI.text = nextWaveText;
int waitT = (int)waitTimeForNewWave;
StartCoroutine(delayXSeconds(waitT));
timeForNextSpawn = waitTimeForNewWave;
auxWaveThisRound--;
waveNumer++;
spawnEnemies();
}
}
else
{
if(aliveEnemies == 0 && auxWaveThisRound <= 0)
{
clearedRoundTextUI.text = clearedRoundText;
roundOver = true;
StartCoroutine(waiterReset());
}
}
accuracy = successfulProjectiles / projectileFired;
}
And the complete function where the above code is
IEnumerator spawnEnemies()
{
int percentForWave=0;
int percentForType=0;
int TotalEnemies = (int)enemySpawnsThisRound;
if (waveNumer == 1)
{
Debug.Log("Entro al wave 1");
percentForWave = 20;
percentForType = 20;
startList = 0;
}
if (waveNumer == 2)
{
Debug.Log("Entro al wave 2");
percentForWave = 70;
percentForType = 70;
startList = endList;
}
if (waveNumer == 3)
{
Debug.Log("Entro al wave 3");
percentForWave = 10;
percentForType = 10;
startList = endList;
}
int enemiesThisWave = Decimal.ToInt32(Math.Round(TotalEnemies * ((decimal)percentForWave / 100), 1));
int enemiesForType = Decimal.ToInt32(Math.Round(lenghtList * ((decimal)percentForType / 100), 1));
endList = enemiesForType + startList;
clonesASpawnear = new GameObject[enemiesThisWave];
int i = 0;
int j = startList;
while ( i < clonesASpawnear.Length)
{
if (j <= endList)
{
if (clonesASpawnear[i] == null)
{
if (sPCurrent == sPMax)
{
sPCurrent = 0;
}
yield return new WaitUntil(() => aliveEnemies < maxAmmoutOfEnemiesOnStage);
clonesASpawnear[i] = Instantiate(enemyTypeList[j], spawnPoints[sPCurrent].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
clonesASpawnear[i].SetActive(true);//lo activo
clonesASpawnear[i].GetComponent<EnemyMovement_DCH>().player = Target;
aliveEnemies += 1;
clonesASpawnear[i].GetComponent<EnemyDamageHandler_DCH>().SpawnerEnemies = this;
j++;
i++;
sPCurrent++;
}
}
else
{
j = startList;
}
}
}
Do not use a while loop. Instead, use "Update()".
void Update() {
if (aliveEnemies < maxAmmoutOfEnemiesOnStage && j <= endList)
{
if (clonesASpawnear[i] == null)
{
if (sPCurrent == sPMax)
{
sPCurrent = 0;
}
clonesASpawnear[i] = Instantiate(enemyTypeList[j], spawnPoints[sPCurrent].transform.position, Quaternion.Euler(0, 0, 0)) as GameObject;
clonesASpawnear[i].SetActive(true);
clonesASpawnear[i].GetComponent<EnemyMovement_DCH>().player = Target;
aliveEnemies += 1;
clonesASpawnear[i].GetComponent<EnemyDamageHandler_DCH>().SpawnerEnemies = this;
j++;
i++;
sPCurrent++;
}
}
else
{
j = startList;
}
}
This is the idea of the Update frame. Logic in here is hit every frame. It will only continue if the number of enemies is below the max. This method MUST go into a class that extends MonoBehaviour, or else it will not be invoked. Given the intended logic, it makes sense that this would be attached to some master "game monitoring" GameObject that is managing the meta of the game along with win states etc.
EDIT (After more content):
Heres one problem "spawnEnemies();". That is an IEnumerator, but you don't use "StartCoroutine(spawnEnemies())". So the method will literally not execute. There will be no errors, but nothing in the method will occur.
In this program, whenever any of the statements under else occur, it doesn't go back to state 0 and perform the actions in that state, which is what I'm trying to do. Instead, the txtStatus, and txtScore boxes just continue to display "Roll again!" which is what is displayed when jumping to state 2. What am I doing wrong here?
int die1 = 0;
int die2 = 0;
int total = 0;
int state = 0;
int point = 0;
//int point2;
int score = 0;
//private int score;
//private int state;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox2_Click(object sender, EventArgs e)
{
}
private void btnRoll_Click(object sender, EventArgs e)
{
picDie1L.Visible = false;
picDie1R.Visible = false;
picDie2L.Visible = false;
picDie2R.Visible = false;
picDie3L.Visible = false;
picDie3R.Visible = false;
picDie4L.Visible = false;
picDie4R.Visible = false;
picDie5L.Visible = false;
picDie5R.Visible = false;
picDie6L.Visible = false;
picDie6R.Visible = false;
Random rand = new Random();
die1 = rand.Next(1, 7);
die2 = rand.Next(1, 7);
total = (die1 + die2);
txtDie1.Text = die1.ToString();
txtDie2.Text = die2.ToString();
txtTotal.Text = total.ToString();
{
if (die1 == 1)
{
picDie1L.Visible = true;
}
if (die1 == 2)
{
picDie2L.Visible = true;
}
if (die1 == 3)
{
picDie3L.Visible = true;
}
if (die1 == 4)
{
picDie4L.Visible = true;
}
if (die1 == 5)
{
picDie5L.Visible = true;
}
if (die1 == 6)
{
picDie6L.Visible = true;
}
if (die2 == 1)
{
picDie1R.Visible = true;
}
if (die2 == 2)
{
picDie2R.Visible = true;
}
if (die2 == 3)
{
picDie3R.Visible = true;
}
if (die2 == 4)
{
picDie4R.Visible = true;
}
if (die2 == 5)
{
picDie5R.Visible = true;
}
if (die2 == 6)
{
picDie6R.Visible = true;
}
if (state == 0)
{
picPuck4.Visible = false;
picPuck5.Visible = false;
picPuck6.Visible = false;
picPuck8.Visible = false;
picPuck9.Visible = false;
picPuck10.Visible = false;
txtStatus.Text = string.Empty;
state = 1;
txtPoint.Text = string.Empty;
}
}
if (state == 1)
{
if (total == 7 || total == 11)
{
txtStatus.Text = "You are a winner!";
score++;
txtScore.Text = Convert.ToString(score);
state = 0;
}
if (total == 2 || total == 3 || total == 12)
{
txtStatus.Text = "You lose. Play again!";
score--;
txtScore.Text = Convert.ToString(score);
state = 0;
}
if (total == 4 || total == 5 || total == 6 || total == 8 || total == 9 || total == 10 || total == 12)
{
txtStatus.Text = "Roll again!";
point = int.Parse(txtTotal.Text);
txtPoint.Text = point.ToString();
state = 2;
if (total == 4)
picPuck4.Visible = true;
if (total == 5)
picPuck5.Visible = true;
if (total == 6)
picPuck6.Visible = true;
if (total == 8)
picPuck8.Visible = true;
if (total == 9)
picPuck9.Visible = true;
if (total == 10)
picPuck10.Visible = true;
}
}
else
{
if (point == total)
{
txtStatus.Text = "You are a winner!";
score++;
txtScore.Text = Convert.ToString(score);
state = 0;
}
if (total == 7)
{
txtStatus.Text = "You lose. Play again!";
score--;
txtScore.Text = Convert.ToString(score);
state = 0;
}
if (total != 7 || point != total)
{
txtStatus.Text = "Roll again!";
state = 2;
}
}
}
}
}
I think you should change the last else statement to this:
if (point == total)
{
txtStatus.Text = "You are a winner!";
score++;
txtScore.Text = Convert.ToString(score);
state = 0;
}
else if (total == 7)
{
txtStatus.Text = "You lose. Play again!";
score--;
txtScore.Text = Convert.ToString(score);
state = 0;
}
else
{
txtStatus.Text = "Roll again!";
state = 2;
}
Explanation: When total has any value but 7 you switch state to 2. Because of that, when you roll again you immediately go the last else statement and execute those 3 if statements inside it. In this scenario, the last if statement is always true (since total is never 7 in this scenario) therefore the text remains "Roll again" and state is never changed (remains 2).
This will fix your issue, but I think you need to change the logic (for example, point is always equal to total, since point == txtTotal.text == total which may not be desired behavior).
Hope this helps.
maybe the problem is here
if (total != 7 || point != total)
{
txtStatus.Text = "Roll again!";
state = 2;
}
as you see the condition is most of the time true! the only time that this is false is when total == point == 7
so i made this simple snake game i made with a guide for as a school project now i want to improve it by adding a score counter and increase the movement speed of the snake every time you get the food help is appreciated
this is the problem i'm currently having
enter image description here
namespace Snake
{
class Program
{
static void Main(string[] args)
{
Console.WindowHeight = 32;
Console.WindowWidth = 64;
int screenwidth = Console.WindowWidth;
int screenheight = Console.WindowHeight;
Random randomnummer = new Random();
int emtiaz = 5;
int bakht = 0;
pixel gz = new pixel();
gz.xpos = screenwidth / 2;
gz.ypos = screenheight / 2;
gz.rangsafe = ConsoleColor.Red;
string movement = "RIGHT";
List<int> xposlijf = new List<int>();
List<int> yposlijf = new List<int>();
int berryx = randomnummer.Next(0, screenwidth);
int berryy = randomnummer.Next(0, screenheight);
DateTime tijd = DateTime.Now;
DateTime tijd2 = DateTime.Now;
string buttonpressed = "no";
while (true)
{
Console.Clear();
if (gz.xpos == screenwidth - 1 || gz.xpos == 0 || gz.ypos == screenheight - 1 || gz.ypos == 0)
{
bakht = 1;
}
for (int i = 0; i < screenwidth; i++)
{
Console.SetCursorPosition(i, 0);
Console.Write("*");
}
for (int i = 0; i < screenwidth; i++)
{
Console.SetCursorPosition(i, screenheight - 1);
Console.Write("*");
}
for (int i = 0; i < screenheight; i++)
{
Console.SetCursorPosition(0, i);
Console.Write("*");
}
for (int i = 0; i < screenheight; i++)
{
Console.SetCursorPosition(screenwidth - 1, i);
Console.Write("v");
}
Console.ForegroundColor = ConsoleColor.Green;
if (berryx == gz.xpos && berryy == gz.ypos)
{
emtiaz++;
berryx = randomnummer.Next(1, screenwidth - 2);
berryy = randomnummer.Next(1, screenheight - 2);
}
for (int i = 0; i < xposlijf.Count(); i++)
{
Console.SetCursorPosition(xposlijf[i], yposlijf[i]);
Console.Write("*");
if (xposlijf[i] == gz.xpos && yposlijf[i] == gz.ypos)
{
bakht = 1;
}
}
if (bakht == 1)
{
break;
}
Console.SetCursorPosition(gz.xpos, gz.ypos);
Console.ForegroundColor = gz.rangsafe;
Console.Write("*");
Console.SetCursorPosition(berryx, berryy);
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.Write("*");
tijd = DateTime.Now;
buttonpressed = "no";
while (true)
{
tijd2 = DateTime.Now;
if (tijd2.Subtract(tijd).TotalMilliseconds > 500) { break; }
if (Console.KeyAvailable)
{
ConsoleKeyInfo toets = Console.ReadKey(true);
if (toets.Key.Equals(ConsoleKey.UpArrow) && movement != "DOWN" && buttonpressed == "no")
{
movement = "UP";
buttonpressed = "yes";
}
if (toets.Key.Equals(ConsoleKey.DownArrow) && movement != "UP" && buttonpressed == "no")
{
movement = "DOWN";
buttonpressed = "yes";
}
if (toets.Key.Equals(ConsoleKey.LeftArrow) && movement != "RIGHT" && buttonpressed == "no")
{
movement = "LEFT";
buttonpressed = "yes";
}
if (toets.Key.Equals(ConsoleKey.RightArrow) && movement != "LEFT" && buttonpressed == "no")
{
movement = "RIGHT";
buttonpressed = "yes";
}
}
}
xposlijf.Add(gz.xpos);
yposlijf.Add(gz.ypos);
switch (movement)
{
case "UP":
gz.ypos--;
break;
case "DOWN":
gz.ypos++;
break;
case "LEFT":
gz.xpos--;
break;
case "RIGHT":
gz.xpos++;
break;
}
if (xposlijf.Count() > emtiaz)
{
xposlijf.RemoveAt(0);
yposlijf.RemoveAt(0);
}
}
Console.SetCursorPosition(screenwidth / 5, screenheight / 2);
Console.WriteLine("bazi ra bakhti, emtiaz: " + emtiaz);
Console.SetCursorPosition(screenwidth / 5, screenheight / 2 + 1);
}
class pixel
{
public int xpos { get; set; }
public int ypos { get; set; }
public ConsoleColor rangsafe { get; set; }
}
}
}
take a look at the following 2 pieces of code
if (tijd2.Subtract(tijd).TotalMilliseconds > 500)
make a variable and use that instead of 500
Than use that variable in the following block
if (berryx == gz.xpos && berryy == gz.ypos)
{
emtiaz++;
berryx = randomnummer.Next(1, screenwidth - 2);
berryy = randomnummer.Next(1, screenheight - 2);
}
and test and make changes and see how your game behaves, it will guide you to what you are trying to do.
Your variable emtiaz is already counting number of times snake gets food
I'm converting my C# Windows Application to a C++\CLI app.
I'm stuck with 'converting' this code:
void LoadWindow(Mode mode) {
if (timer != null && timer.Enabled) return;
int currentIndex = Windows.IndexOf(panel.Controls[0]);
int loadInex = 0, exitLeft = 0, entranceLeft = 0, stopLeft = 0;
if (mode == Mode.Next)
{
loadInex = currentIndex == Windows.Count - 1 ? 0 : ++currentIndex;
exitLeft = -((panel.Width / 2 - Windows[currentIndex].Width / 2) + Windows[currentIndex].Width);
entranceLeft = panel.Width;
}
else
{
loadInex = currentIndex == 0 ? Windows.Count - 1 : --currentIndex;
exitLeft = panel.Width;
entranceLeft = -panel.Width;
}
stopLeft = panel.Width / 2 - Windows[loadInex].Width / 2;
Windows[loadInex].Left = entranceLeft;
panel.Controls.Add(Windows[loadInex]);
timer = new System.Windows.Forms.Timer();
timer.Interval = 10;
timer.Tick += new EventHandler(delegate(object sender, EventArgs e) {
if (mode == Mode.Next)
{
if (exitLeft <= panel.Controls[0].Left)
panel.Controls[0].Left -= 50;
if (stopLeft <= panel.Controls[1].Left)
panel.Controls[1].Left = panel.Controls[1].Left - 50 < stopLeft ? stopLeft : panel.Controls[1].Left - 50;
if (exitLeft >= panel.Controls[0].Left && stopLeft >= panel.Controls[1].Left)
{
panel.Controls.RemoveAt(0);
timer.Enabled = false;
}
}
if (mode == Mode.Previous)
{
if (exitLeft >= panel.Controls[0].Left)
panel.Controls[0].Left += 50;
if (stopLeft >= panel.Controls[1].Left)
panel.Controls[1].Left = panel.Controls[1].Left + 50 > stopLeft ? stopLeft : panel.Controls[1].Left + 50;
if (exitLeft <= panel.Controls[0].Left && stopLeft <= panel.Controls[1].Left)
{
panel.Controls.RemoveAt(0);
timer.Enabled = false;
}
}
});
timer.Enabled = true;
}
AFAIK C++\CLI doesn't support anonymous methods (I can't even take advantage of lambdas).
This wouldn't be a problem if the EventHandler delegate didn't use local variables in the LoadWindow function.
How can I implement this? I considered using a simple functor class, but is there a more 'elegant' way?
Thanks,
Alex