I'm trying to make a model that acts like sub-atomic particles for an interesting project. I understand that C# isn't exactly the best coding language for this kind of undertaking, however since I'm pretty newish to coding and only now C# and Java I decided I would just try on C#.
Currently what I'm trying to do is get the ovalShape, representing a particle, to passively move towards oppositely charged particles. To get this to run in the background all the time I decided to use threads, but when I ran my simple test for proof of concept of moving the ovalshape with a thread, it didnt move at all and I don't understand why.
I set up the thread normally using
Thread thrFOA = new Thread(new ThreadStart(ForceOfAttraction));
and then made my test background function:
public void ForceOfAttraction()
{
ovalShape1.SetBounds(ovalShape1.Location.X + 1, ovalShape1.Location.Y, ovalShape1.Width, ovalShape1.Height);
ovalShape1.Refresh();
}
So I thought this should just make it so that the oval slowly moves across the screen, being moved a pixel at a time, however there was no movement at all and I don't understand why not. I also tried this.Refresh(); instead of ovalShape1.Refresh(); as it is in the form class, but the same result.
I appreciate the time and help, thanks!
Related
I am an inexperienced programmer, I am looking for advice on a new unity project:
I need to generate terrain for a 3d game from fairly large tiles. For now I only need one type of tile, but I was thinking, I better set up a registry system now and dynamically generate that default tile in an infinite grid. I have a few concerns though, like will the objects continue to load as the character moves into the render distance of a new tile (or chunk if you rather). Also, all the tutorials I have found are wrong for me in some way, like it only works in 2d and doesn't have collision, or is just a static registry and does not allow for changing the content of the tiles in-game.
Right now I don't even know what the code looks like to place a 3d object in the scene without building them from vectors, which maybe I could do. I also don't know how I would want to trigger the code.
Could someone give me an idea of what the code would look like / terminology to look up / a tutorial that gives me what I need?
This looks like a pretty big scope for a new programmer but lets give it a shot. Generating terrain will be a large learning experience when it comes to performance and optimization when you don't know what you're doing.
First off, you'll probably want to make a script that acts as a controller for generating your objects and put this inside of the player. I would start by only making a small area, or one chunk, generate and then move on to making multiple chunks generate when you understand what you're doing. To 'place' an object in your scene you will want to make an instance of the object. I'd start by trying to make your grid of objects, this can be done pretty easily on initialization (Start() function) through a for loop, for testing purposes. IE, if you are trying to make 16x16 squares like minecraft; have a for loop that runs 16 times (For the x) and a for loop inside of that to run 16 times (for the z). That way you can make a complete square of, in this case, cubes. Here is some very untested code just to give you an example of what I'm talking about.
public GameObject cube; //Cube you want to make a copy of, this will appear in the editor
void Start(){
for(var x=0; x < 16; x++){
for(var z=0; z < 16; z++){
GameObject newCube = Instantiate(cube); //Creates an instance of the 'cube' object, think of this like a copy.
newCube.transform.position = new Vector3(x, 0, z); //Places the cube on the x and z which is updated in the for loops
}
}
}
Now where you go from here will be very different depending on what you're trying to do exactly but you can start by looking into perlin noise to add in a randomized y level that looks good. It's very easy to use once you grasp the general concept and this example I provided should help you understand how to use it. They even give good examples of how to use this on the Unity docs.
In all, programming is all about learning. You'll have to learn how to only take the parts of resources that you need for what you're trying to create. I think what I provided you should give you a good start on what you want to create but it will take a deeper understanding to carry things out on your own. Just test different things and truly try and understand how they work and you'll be able to implement parts of them into your own project.
I hope this helps, good luck!
There is the whole super simple C# console app here:
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int left = 0;
Console.SetCursorPosition(++left, 0);
while (true)
{
ConsoleKeyInfo stisknutaKlavesa = Console.ReadKey(true);
if (stisknutaKlavesa.Key == ConsoleKey.RightArrow)
{
Console.SetCursorPosition(++left, 0);
Console.Write("#");
}
}
}
}
}
Description: When I press RIGHT KEY (and hold it!!) it quickly writes one hash, then there is a pause, and then it fluently keeps writting another hashes further.
How can I get rid of that pause? I have been dealing with identical problem in one of my winform app, but for simplicity I posted it in this console application here.
I have found some answers about this topic but all of them were about javascript (jquery) and i did not understand how to apply it on this my c# project.
And i do not want to resolve it in asynchronous way either. Is there such a solution, please?
This comes from the way that the windows console (and most other text-based inputs in Windows and other environments) behaves. If you put your cursor on any text input (like your browser's address bar, for instance), and press and hold an arrow key, you will see it move once, pause, and then start moving repeatedly with a much shorter pause.
In effect, your console's ReadKey registers keypresses based on some predefined behaviors of the operating system.
If you want to be able to detect and respond to someone holding a key down, you'll need to use a medium that gives you more low-level access to events like keydown and keyup. Something like Windows Forms, WPF, Unity... pretty much anything that's not Console.
Furthermore, if you want to respond to those key-down and key-up events using timing that's different from how the system treats those events, you'll have to create your own timing mechanism, and only use those events to help you know when things have changed. Examples of this can be found here and here.
If you're trying to make something akin to a video game, you might consider looking into libraries that are specifically designed for these use cases, like Unity3D.
I am making project for school "simulation of intersection" and i need few advices.
Canvas is a parent.
For now i have created class "Car" which contains some properties like Rectangle(body), Speed, Enums (Car type, Direction of moving etc.). So:
What is a best way to move objects in wpf? (I think about DispatcherTimer, but here is a question - each for one object or just one and just in one tick move all objects?)
I have some problem with some math i mean how to create a animation of turn. Tried to find this, but all i found was some spirals. I know there will be some use of Math Class + angle. (Some code, ideas or keywords for search would be nice.)
Sry for english if someone will have troubles to understand what i wrote.
The usual way it is done in games is by having one main loop. You can do this in WPF just the way you mentioned - make a DispatcherTimer, and update their position all during one call. Creating more timers is needlessly consuming resources for hardly any benefit.
Real car physics are relatively complex, but for your use case, you can go with something really simple. This is a great (and short) article on simple but good looking car physics: http://engineeringdotnet.blogspot.com/2010/04/simple-2d-car-physics-in-games.html
You can use XAML or Code behind to make animation. Here
I'm having a little trouble concisely describing what it is that I'm trying to do, which is hurting my ability to search for an answer. I'll try to be specific with my problem, if anyone could give a suggestion or point me in the direction of what to study, I'd greatly appreciate it.Tr
I'm trying to program a GUI version of the cardgame Dominion, where playing different cards will yield different results and choices. Many of these cards have similar starting choices (e.g. select a card from your hand and trash it/look at enemy hand), but different ending choices (e.g. upgrade that trashed card/give trashed card to another player). upon playing a card, the program looks for the unique numeric card code and begins executing code specific to that card.
Here's where I'm hung up:
I'd like to have more general methods that listen for user input INSIDE the unique card-code, but I keep getting errors. Ideally, I'd be able to do something like
for(int i = 0; i < totalPlayers; i++)
{
showEnemyHand(i);
}
or
for(int i = 0; i < totalPlayers; i++)
{
thiefEffect(i);
}
within a 'buttonclicked' event (the "play card" button, specifically.) The showEnemyHand(int) and thiefEffect(int) method would wait for user input, store responses, and then return right back to the for loop that it was called from, but its not as easy as I'd originally hoped.
I'm suffering most from not even knowing what it is that I should be searching for. I've been reading up on event handling and delegates, and I'm not sure that's what I need. Can anyone point me in the direction of what I need to learn, or maybe give me the topic of what I'm trying to solve so I can search for it a little easier? (of course, helping me solve it would be appreciated too =D)
Thanks a bunch!
Jake
Your solution would be fine for a command line based game, in a language with continuations/coroutines, or maybe in a multi-threaded application where showEnemyHand etc would block on user input. For a GUI-based game, an event driven architecture is really what would work best for you, so in principle I'd suggest learning more about it.
But if you really want to do that using a loop, I'd suggest then reading about threading and blocking calls. Once you understand the concepts, you should be able to:
Create a separate thread to host your loop;
Create a lock that will block execution until the user inputs something (see the example in the linked question);
Use that lock in your loop and on the callback for user input:
In the beginning of your loop, you wait on your lock;
When the user inputs something (which you'll detect using an event handler - see the docs for the particular GUI framework you're using) you save which action was chosen and frees the lock;
Your loop will automatically continue, reading the saved action and performing an iteration, until it reachs the same point again and waits for another user input.
Whether this method is easier or harder than coding your rules using the event driven logic, it's debatable. The same can be said about coroutines (though being less experienced with that, I can not opinate). The pointers I gave should help you get started though.
I'm developing for xna game studion using XNA 3.1, and I've noticed a problem with some games, where they lag despite the system having plenty of resources to handle them, along with an inexplicable excess of processor usage. When the window from the game is in focus, process #1 (in task manager) goes to 100% usage, and the game shows signs of minor lag (largely notable when sound effects are repeated in sequence). When the game loses window focus, it continues to draw and update at real time, but the process usage decreases, and the lag disappears.
I have tested this with various games, and the results remain the same, proving that it has nothing to do with my code or code efficiency.
Is this a problem isolated to Xna 3.1, and is there fix for it? Or do I just have to switch to 4.0 and hope my games don't use anything that isn't backwards compatible?
The problem may occur because of garbage collector. Everytime garbage collector runs, the frame rate may drop for a second or two, though on Windows it shouldnt be a problem.
Add this line to your code and see how much heap memory is generated. Every time the value goes down, garbage collector is ran.
SpriteBatch.DrawInt64(FONT, GC.GetTotalMemory(false) / 1000 /* in kilobytes */, new Vector2(5, 30), Color.White, 0f);
SpriteBatch.DrawInt64 is a SpriteBatch extension which doesnt generate garbage on int, long etc. You can alternatively just use SpriteBatch.DrawString(..., (GC.GetTotalMemory(false) / 1000).ToString(), ... )
SpriteBatchExtensions.cs : http://pastebin.com/z9aB7zFH
XNA, from my experience, runs up to 60 frames per second while in focus, and at about 20 frames per second when out of focus. IF however, you have set IsFixedTimeStep = false; the game will run as fast as it possibly can when the process is in focus. With my game, on my machine, it runs at about 500-700 fps. This is also tied in to the number of Update() calls that occur. So my game is also updating 500-700 times per second.
My bet is that you have disabled the fixed timestep, and the massive number of Update and Draw calls are consuming 100% of your core and it is messing with your music. I would recommend removing the line IsFixedTimeStep = false; if it's there. If that line does not exist in your code, this is not the problem, although I would bet that your Update or Draw is doing more work than it should be.
Just noticed this in my own game, I have a Console.WriteLine statement (for debugging) in my update loop, this causes lots of lag.
XNA add a sleep when the window is not in focus!
I solved this problem some time ago overriding Game class and changing the way the Game class understand its form is active or not.
There is not way, as much as i know, to disable this behaviour without modifying Game class behaviour with code.
In particular, the way i found some time ago is a real hack\quirk!
Very unclean solution, but the only way i found.
public class MyGame
{
private MethodInfo pActivate;
public MyGame()
{
// We need to access base HostActivate method, that unfortunally, is private!
// We need to use reflection then, of course this method is an hack and not a real solution!
// Ask Microsoft for a better implementation of their class!
this.pActivate = typeof(Game).GetMethod("HostActivated", BindingFlags.NonPublic | BindingFlags.Instance);
}
protected sealed override void OnDeactivated(object sender, EventArgs args)
{
base.OnDeactivated(sender, args);
// Ok, the game form was deactivated, we need to make it believe the form was activated just after deactivation.
if (!base.Active)
{
// Force activation by calling base.HostActivate private methods.
this.pActivate.Invoke(this, new object[] { sender, args });
}
}
}