I'm making a 2D game using Monogame. My character loads to the game fine, however when a user presses the T key, I want my character to reload again (As if the character has teleported.)
I have loaded the player content in the LoadContent() function like so:
player.Load(Content);
And in the Draw() function, I have tried to reload the character again when 'T' is pressed by doing:
if (Keyboard.GetState().IsKeyDown(Keys.T))
{
player.Draw(spriteBatch);
}
and/or,
if (Keyboard.GetState().IsKeyDown(Keys.T))
{
player.Load(Content);
}
but neither of these seem to work.
My question is, what is the correct way to successfully load the character again and where do I place this if statement?
UPDATE:
Here's my player.Load() method used in the player class:
public void Load (ContentManager Content)
{
texture = Content.Load<Texture2D>("danPlayer");
}
You already have a function for loading the character, which is good. Now:
1) The Draw function is meant for drawing. It's running (kind of) async from the game. All your game logic should be in the Update function.
2) You have to know how to check if a keyboard button is clicked, not if it is being held down, because this way, the character will Load as long as you are holding the 'T' key. No matter how fast you click 'T' key, the way you are doing it, you'll fire the Load function at least 2-3 times.
3) To check this, you'll need 2 variables holding the current and the last state of keyboard, and all your game logic should be in between the updates for new and old keyboard state. You could also create a simple function to check for Click(Keys key) and Hold(Keys key)
KeyboardSate ksNew, ksOld;
protected override void Update (GameTime gameTime)
{
ksNew = KeyboardSate.GetState();
*your logic here*
if (Click(Keys.T))
player.Load(Content);
ksOld = ksNew;
}
private bool Click(Keys key)
{
return ksNew.IsKeyDown(key) && ksOld.IsKeyUp(key);
}
private bool Hold(Keys key)
{
return ksNew.IsKeyDown(key);
}
If you're using XNA the usual way, you don't want to call Load to reload the player. That function is usually used only to load the player's assets, primarily images.
Somewhere in your code there should be some method where you're initializing aspects of your player, such as position and perhaps some sort of state. What you do is you want to call that code whenever T is pressed.
I would refer to Monset's answer about how to go about getting your keypress. I would also recommend picking up a book on XNA, since most of your questions that I've seen on SO have been about things that are often covered in such books. The one I initially learned from was Learning XNA, which seems like it might be your speed.
Related
is there a way to move an object in Unity3d from one place (target1) to an other (target2.. so on) by pressing a key?
I used...
private void FixedUpdate()
{
if (Input.GetKey("s"))
{
transform.position = target1.position;
}
}
...to move the Object form Start to the first target but if just would write another if statement the object would go directly to the target 2... :(
I want: Object moves from target1 to target2 to target3 and so on by pressing "s"
i hope someone can help me :)
What I'm understanding is either you want to have an array of places for your object to go, or you want the object to move a set amount each time you press a button. I will give an example and an explanation for each of these.
You want to move an object to different points, and not a specific amount each time.
First off, you could use an array, and fill it with the places for the object to go, in order.
Then, you could have a public variable for looping through the array everytime you press the button. Now, instead of Input.GetKey("s"), which has several problems, you want Input.GetKeyDown(KeyCode.S), because GetKeyDown only fires when you press the key, and GetKey fires every frame the key is pressed. You also want KeyCode, because that's what the KeyCodes are made for. Example code:
public class ExampleScript : MonoBehaviour
{
public int index = 0;
public Vector3[] positions = new Vector3[the amount of positions you have];
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
transform.position = positions[index];
index++;
}
}
}
You want to move a fixed amount.
Use the same code, but without the array and int, and instead a Vector3 for how much you want to move. Then, in GetKeyDown, you'd do something like transform.position += moveAmount.
:)
PS: when asking a question on Stack Overflow, you should add a little bit more details, but it was a pretty good question, especially compared to others that I've seen.
The Context:
I'm currently creating a melee combo system for my 2D RPG. The first time a player attacks will trigger the first attack animation and if the player chooses to attack a second time, it ill trigger the second attack animation. I got the system to work by calling an attack function that passes a string parameter depending on which animation I need to be played.
So the ComboOrder function will be called every frame to order the animations and once the player presses the "E" key, the Attack function will be called with either "Attack-1" or "Attack-2".
The Problem: The code and animations work fine however, after many changes to other parts of the game I noticed, I get a warning every time I press the "E" key. What I changed was completely unrelated ti this so I don't see a connection from that to the warning.
Parameter" does not exist
Solutions I have tried: I've searched the web for answers, however, none of them fit my issue. It seems that Unity thinks I'm passing the string " which would indicate a syntax error but I've double-checked my code and I can't find anything of sorts. I've also heard that it has been a bug in Unity but they never told how to fix it. Is there anything I can do if that were the case?
Here's the code:
void ComboOrder() {
if (comboIndex == 1)
{
if (Input.GetKeyDown(KeyCode.E)) // Attack Input
{
Attack("Attack-1");
comboIndex++;
}
} else if (comboIndex == 2) {
if (Input.GetKeyDown(KeyCode.E)) // Attack Input
{
Attack("Attack-2");
comboIndex--;
}
}
}
public void Attack(string attack)
{
animator.SetTrigger(attack);
}
And here are the Animator settings for the player:
So after not being able to work on the game for about two weeks, I came back to take a closer look and realized it was what you said, there was an animation event calling the function without passing a parameter and since it was not coded, I never caught it. Thank you to everybody who helped.
I'm not sure how to switch scenes and bring all of my resources with me. I do understand that upon load of new scene, the previous scene gets destroyed on load. I've explored some with DontDestroyOnLoad() but had no luck with what I'm trying to do.
I tried to make my player controller a prefab and simply put him into the next scene; however, I returned a heck of a lot of errors because of the many scripts I have. Mostly stuff like checkpoint, HP bars, and even the weapon.
What I need to know is how to import everything into the next scene. How do I do this without having to recode or even re-make all of the stuff that I need?
You're looking for LoadSceneMode.Additive. This is the second parameter of the LoadScene method and will load the new scene into the current one.
If you need to import every object from the previous scene, then what's the point in creating a new one?
What you could do is saving the objects positions into a file and then loading that file back on the next scene or try (again) with DontDestroyOnLoad();
I recommend to check the documentation of Unity about this function.
If you want an individual object not to be destroyed on the scene change then on the void Awake() function of Unity make a DontDestroyOnLoad(this.gameObject);
Could you provide more information? I ask because it seems from your description that
DontDestoryOnLoad
should accomplish what you want but you say it does not. As long as the object holding the components whose states you want to save is persisted into the next scene using that method, then all of those components' states should be persisted as well. Please elaborate and we can possibly provide a better answer. As for how to use it to save the state of every game object:
GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
foreach(GameObject go in allObjects) {
if (go.activeInHierarchy) { /* and any other logic you want. Maybe like !isTerrain */
Object.DontDestroyOnLoad(go);
}
}
For the above code, I ripped it from https://answers.unity.com/questions/329395/how-to-get-all-gameobjects-in-scene.html
If for instance I have a game which consists of just a single scene, and in that scene I make the user chose between the normal play mode or the tutorial play mode. The game has 4 different objects: a ball, 4 squares and a squarecontroller. In the tutorial mode i want to provide the user with a pointing arrow while pausing the game and continue after the user pressed the object being pointed at. Should I make a script for the normal mode and another one for the tutorial mode, make one script and check if a tutorial boolean is true or false in every function (boolean should be true if user pressed the tutorial button) or do some kind of preprocessing?
In the squarescript for example:
void OnCollisionEnter2D () {
if (isTutorial) {
PauseGame();
arrow.position = GetRelativePosition();
arrow.setActive(true);
} else {
if (canCollide) {
score++;
} else {
GameOver();
}
}
In the ballscript:
void OnMouseDown () {
if (!isTutorial) {
return;
}
ResumeGame();
}
We know nothing of your game so it's hard to answer. But as a rule of thumb: The less you have to type, the better. Also consider what will happen if you need to add new functionality to the game, will you have to go back and change tons in your code?
If so, you are most likely not writing good code.
As an attempt to give a concrete answer I'd say you should make an inheritance, create a class Level and make sub classes Tutorial and FreePlay or similar, that inherits from Level.
Then you can add all "general" functionality in the base class and the specific things goes in the sub classes
By structuring these behaviours inside if statements, it makes the code hard to understand and work with. Imagine what this will look like if you decide you want one of the squares to increase the players score AND show a tutorial arrow.
Split the behaviours into separate objects. For the square it could be something like a TutorialCollisionHandler, ScoreCollisionHandlerand HazardCollisionHandler. Then you can create different squares simply by changing which collision handlers are added to them, you don't even need to write any code!
Now depending on which mode the user picks, you can just use a different mix of squares. The same principle can be used with other tutorial or game specific behaviour.
I am using Farseer 3.3 and XNA.
I have a problem that i just cant solve in a nice way.
I have a situation where there is a world with bodys in it all working away doing there thing.
I then have an object thats body is set to not enabled, is there a nice way of checking if the body is currently colliding with anything? i.e. to know if it would be a clean spawn should I make it enabled and set it to dynamic?
Thanks in advance.
For anyone else finding this post while trying to solve the same kind of problem here is how I did it in the end.
In this example I use the word Item to represent the class that contains a body etc, this could be your player / bullet / whatever.
In your Item class subscribe to the bodies on collision and on separation events.
this.Body.OnCollision += Body_OnCollision;
this.Body.OnSeparation += Body_OnSeperation;
then setup a member for the item to hold a count of collisions and separations.
private int _canBePlacedCounter = 0;
On the event handler methods, increase of decrease the member count. In the code below there are extra conditions as for myself, I only want to perform these operations when an item is being placed into the "world".
private bool Body_OnCollision(Fixture fixturea, Fixture fixtureb, Contact contact)
{
if(this.IsBeingPlaced)
{
_canBePlacedCounter++;
}
return true;
}
private void Body_OnSeperation(Fixture fixturea, Fixture fixtureb)
{
if (this.IsBeingPlaced)
{
_canBePlacedCounter--;
}
}
We then can setup a simple public property (this really should be a method if we want to get into coding standards but this is not the time or place)
public bool CanBeDropped
{
get
{
if (_canBePlacedCounter == 0) return true;
else return false;
}
}
The reason for this implementation is, I originally had a bool which I set to true or false whenever I got one of the events. The problem is... If your item collides with item A, then collides with item B then leaves item A you get a reading of not colliding. So... using a counter like this we can count in and count out all of the collisions and separations. Belive me this works like an absolute charm.
Hope it is of use to someone out there.
UPDATE: I have found that this only works well with basic rectangles. If you get into bodies with many polygons such as those automatically generated from images its very unreliable as for whatever reason farseer regularly raises less separation events than it does collision events meaning the counter often does not return to 0.