How To Ignore Collision Between Two Objects On The Call Of A Script In Unity3D? - collision

Basically, what I want to do is have two objects (fpscontroller and a wall) that collide like normal. But, once a script runs, they won't collide anymore.
So, how do I make that script that makes the two objects ignore collision with each other? I've tried looking this up, and what I got was Physics.IgnoreCollision, but the documentation on that confused me. And when I tried putting it in and replacing their variables with my variables, I got a bunch of errors.
So, please help.

The way i would go about doing this is through layers.
In unity, a convenient way to ignore physics collision between objects is through setting the object to be ignored to a layer which your player object will always ignore.
So, to go about setting this up imagine the following:
fpscontroller's layer is set to "player" (a layer i have created and named such).
wall's layer is initially always set to "wall" (once again a layer i have created)
Additionally, I create a layer that i call "IgnorePlayerCollisions"
Now i go to: Edit > Project Settings > Physics
Here i can check the box which will turn off collisions between my player and IgnorePlayerCollisions layers.
Now, at runtime i run my script which says:
Change Wall Layer to "IgnorePlayerCollisions". Voila, my player now ignores all collisions with this layer.
Code Examples: (You don't need these all):
// Function to Change a GameObject Layer to the Ignore Layer
public void ChangeGameObjectLayerToIgnore(GameObject go) {
go.layer = [Index of Ignore Layer];
}
// Function to Change "This" GameObjects layer to any other layer
public void ChangeThisGameObjectLayer(int layerIndex) {
this.gameObject.layer = layerIndex;
}
// Change a GameObject layer to another layer
public void ChangeGameObjectLayer(GameObject go, int layerIndex) {
go.layer = layerIndex;
}
How?
Place a C# function into a script and attach it to either your desired gameobject. In your case, i may attach it my Player GameObject since it seems like you may want to disable object throughout the game based on specific trigger or something. It really depends on how you plan to trigger the function.
Let me know if this makes sense or not. If not, i can attempt to make it more legible.
Good luck and have fun!

Related

Second client's canvas not registering input? Unity

Obligatory "i'm very new". I couldn't figure out how to hook up a canvas that the player interacts with (chooses which team they'll be playing on in the game) that I had would work out if it was in the scene that the player prefab would be spawned into. So I put the canvas into the prefab with the player and set it as inactive once they select which team.
It works flawlessly for the host client (changes their "playerTeam" int and spawns them where they should be spawned) but when the second client joins their canvas is there, but won't take any input. I know it's this because the debug.log i put in right after input is not being run. here are the code segments that are necessary.
i have the canvas disabled by default and activated after an (isLocalPlayer) run on a script on the parent object. I can't add a networkID to the canvas because the prefab parent object has the networkID and they both can't have one, which means I cannot use (isLocalPlayer) on the canvas script, which may be the issue. But I also can't have the canvas on the actual level screen because even if i find the game object of the canvas, i don't know how to make it find which player to assign the playerTeam int to.
The following is run on a script attached to the canvas (of which the empty player object is the parent of)
Button CT = chooseCT.GetComponent<Button>();
CT.onClick.AddListener(parent.GetComponent<Sync>().CmdpickedCT);
and this is the code that runs on a script on the parent object
[Command]
public void CmdpickedCT()
{
GetComponent<Movement>().playerTeam = 2;
teamSelector.SetActive(false);
}
I apologize if I'm missing something big here. Thanks for any help.
for more information i have more stuff in the movement script run once the playerTeam is set to something other than 0, this also works on the host. Any other information you can give about how to pass info from the objects in the game scene to the instantiated objects would be great too. Thanks again.
Additional information, it seems like if i have both the second client and first client on the canvas at the same time, I cannot choose my team with either. It says "Trying to send command for object without authority".

Where should a game logic be within a JavaFx application?

Being new to Javafx and java, I'm having trouble picturing the design for a chess game.
So I have the start method like following in my JavaFX Application-extended class:
public void start(Stage primaryStage) throws Exception{
Scene scene = new Scene(createContent());
primaryStage.setTitle("ChessGame");
primaryStage.getIcons().add(new Image("file:images/icon.png"));
primaryStage.setScene(scene);
primaryStage.show();
}
protected Parent createContent(){
Pane root = new Pane();
root.setPrefSize(WIDTH*TILE_SIZE, HEIGHT*TILE_SIZE);
boardInitialize("8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -");
root.getChildren().add(tileGroup);
root.getChildren().add(pieceGroup);
return root;
}
The problem is, I don't know where to put the game's logic inside my application. The game logic will handle player's turn, check for checks and checkmates, generate possible moves, etc (and later a very crude AI if possible). I have tried to jam it into the start method, but it doesn't work because the start method only runs once. Pygame with their gameloop makes much more sense than this and I can see how I would go with it. So my question is: where do I put the game logic in my application?
You may use the Model-View-Controller (+ Network if needed) architecture to design your system. JavaFX is really useful when working with the MVC.
Rules of Thumb:
1- Do not put your game logic inside the Model, Network and View(FXML) classes.
2- Use FXML as part of the design (it will bootstrap your work).
3- Try to achieve " Low coupling & High Coherence "
4- Some example from a fully-working MVC JavaFX project.
> /* WelcomeScreenController class (interacts with the FXML file)*/
> #FXML
> void doSignup(ActionEvent event) {
>
> user = username.getText();
> pass = password.getText();
>
> if(user != null && !user.isEmpty() && pass != null && !pass.isEmpty())
> if (checkBox.isSelected())
> GameEngine.game().getAccessManager().callSignupService(user,pass);
> else
> showNotification("You need to accept terms.");
> }
5- Try to handle button logic from the Controller class of the particular FXML file. http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm
6- Create a controller class named "GameEngine" to do all your computations about the game logic. Call GameEngine's methods from the button's handle action event method.
7- Try to use Object-Oriented Programming methodologies. (Polymorphism, Inheritance, Design Patterns, etc.)
I would stand upon the shoulders of others and use a library that already has some structure in it.
With that you can follow the model that build upon the experience of others and use their best practices and avoid the pitfalls they have experienced.
For JavaFX I am aware of the FXGL library, which comes with a nice list of examples of how to build a game in JavaFX.
On YouTube you can find several examples and tutorials for this library.
First of all, I would like to let you know that I have never written a Javafx application and I could be wrong.
The start method, as you correctly pointed out is the main entry point of a Javafx application, as you can see from the anatomy of a Javafx application described here. You can initialize your game there, but naturally, the moves will occur later than running the start. You will need to use event handling to handle the case when a move is being attempted by a player.
Once you are able to handle the move events, you will also be able to check whether a move is correct or not, or, to check the possible valid move options of a given player. I would like to suggest that you should have your own classes for the business logic and to avoid mixing business logic with event handling, even though the event handler will invoke business logic methods.

Unity global mouse events

Most Unity tutorials suggest using Mouse events within the Update function, like this:
function Update () {
if (UnityEngine.Input.GetMouseButton(1)) {
}
}
This strikes me as really inefficient though, similar to using onEnterFrame in AS or setInterval in JS to power the whole application - I'd really prefer to use an events based system.
the OnMouseDown() method is useful, but is only fired when the MouseDown is on the object, not anywhere in the scene.
So here's the question: Is there a MouseEvent in Unity for detecting if the mouse button is down globally, or is the Update solution the recommended option?
This strikes me as really inefficient though, similar to using
onEnterFrame in AS or setInterval in JS to power the whole application
- I'd really prefer to use an events based system.
As already pointed out in comments, this isn't necessary less efficient. Every event based system is probably using a polling routine like that behind the scenes, updated at a given frequency.
In many game engines/frameworks you are going to find a polling based approach for input handling. I think this is related to the fact that input update frequency is directly correlated to the frame rate/update loop frequency. In fact it doesn't make much sense to listen for input at higher or lower frequency than your game loop.
So here's the question: Is there a MouseEvent in Unity for detecting
if the mouse button is down globally, or is the Update solution the
recommended option?
No there isn't. Btw if you want you can wrap mouse input detection inside a single class, and expose events from there where other classes can register to.
Something like:
public class MouseInputHandler : MonoBehavior
{
public event Action<Vector2> MousePressed;
public event Action<Vector2> MouseMoved;
...
void Update()
{
if (Input.GetMouseButton(0))
{
MousePressed(Input.mousePosition);
...
}
}
}
Like stated, you can use it without major concerns, Unity will 'make its magic' internally as to set processing power sensitive code execution for you in terms of polling events. That's the beauty of a modern game engine after all. You normally shouldn't have to be hacking your way around a common feature such a mouse click detection.
However if you don't want to go using the main Update() you can make a CoRoutine if you feel more comfortable with that, just bear in mind that Unity coroutines are not multi-threaded neither, so at the end everything needs to wait anyway.

How to fix overlapping objects on the stage in AS3

I have a flash game where I have a picture designed to be the textbox for a prompt and textbox inside with the relevant text but the textbox is being hidden by the image. Anyone know how to make is so that the textbox is guaranteed to be on top or whatever I need to do to keep this from happening?
The other answer using setChildIndex will definitely work, however, I think a different design approach is really what you should be doing to remove the headache altogether.
For example in a game I might have different layers such as :
backgroundLayer
gameLayer
interfaceLayer
Those 3 Sprite layers would get added to the stage in that order. I would then add display objects to the appropriate layers. So anything I added to the backgroundLayer or gameLayer would ALWAYS be 'behind' my user interface on the interfaceLayer.
That allows you to not have to worry about the layering constantly. The answer with setChildIndex will fix the problem for that moment, but should something else be added to the container it will overlap your textbox, which is something I don't assume you want.
here's an example :
var backgroundLayer:Sprite = new Sprite;
var gameLayer:Sprite = new Sprite;
var interfaceLayer:Sprite = new Sprite;
addChild(backgroundLayer);
addChild(gameLayer);
addChild(interfaceLayer);
now, whatever you add to interfaceLayer, will ALWAYS be on top of objects you add to gameLayer or backgroundLayer.
So in the case of your text box, just add it to your interfaceLayer and any other objects you want behind it, you add to the gameLayer or backgroundLayer.
The order of adding display objects to display object containers effect their z-order, in other words the front to back order. The last added display object becomes the frontmost. So the child index of the children of a display object container is important for drawing of overlapped children.
If you put picture and text on the same DisplayObjectContainer such as a MovieClip:
Lets say your DisplayObjectContainer is mc.
And your textbox is txt
Please try this:
mc.setChildIndex(txt, mc.numChildren-1);

Tetris and pretty graphics

Say you're building a Tetris game. As any proper programmer, you have your view logic on one side, and your business logic on the other side; probably a full-on MVC going on.
When the model sends its update(), the view redraws itself, as expected.
But then... if you wanted to add, say, an animation to vanish a line, how would you implement that in the view?
Make any assumptions you want---excepting that "Everything is properly encapsulated".
Personally, I would separate draw the screen as often as possible, even if there was no update of the block position. So I would have a loop somewhere with an "update" and a "render" part. Update plays the ball to the logic which does or does not any update of positions and/or block removal. Render plays the ball to the graphics part, which draws the blocks where they should be.
Now if there are lines to erase, the logic knows and can mark those lines to be removed. I assume here, that every piece consists of 4 single blocks and any of these blocks is a single object. Now when this block has the "die"-flag set, you may take some render-parts to vanish the block (let's say, 500ms to explode). After this time, the object may be disposed and the block a line above falls down. Why 500ms? Well, you should definitely use time-based movement as this keeps the game speed the same on different computers.
Btw, there are already so called game engines which provide such an update-render-loop. For example XNA, if you go the .NET line. You may also code your own engine but beware, it's not an easy task and it's very time consuming. I did this once and don't expect it to be an engine like the Source Engine ;-)
Most games execute a loop that constantly redraws the view of the game as fast as possible, rather than waiting for a change in the model state and then refreshing the view.
If you like the model view pattern, then it might work well for the view to continue to draw some types of objects after they are removed from the model, fading them out over a few milliseconds.
Another approach would be to combine class MVC with something like differential execution - the 'view' is a model of what is presented, but the drawing code compares the stream of events the 'view' creates with the stream from the previous rendering. So if in one stream there's a line, and the next there isn't, the drawing code can animate the difference. This allows the drawing to be abstracted away from the view . Frequently the 'view' in MVC is a collection of widgets, rather than being something which draws the display directly, so you end up with nested MVC hierarchies anyway: the application is MVC ( data model, view objects, app controller ), where the view object has a collection of widgets each of which is MVC ( widget state (eg button pressed ), look and feel/toolkit binding, mapping of toolkit events -> widget state ).
I've often wondered this myself.
My own thoughts have been along this line:
1) The view is given the state of the blocks (shape, yada-yada), but with extra "transitional" data:
2) The fact that a line must be removed is encoded in the state, NOT computed in the view.
3) The view knows how to draw transitions now:
No change: state is the same for this particular block
Change from "falling" to "locked": state is "locked in" (by a dropping block)
Change from "locked" to "remove": state is "removed" (by a line completion)
Change from "falling" to "remove": state is "removed", but old state was "falling"
Its interesting to think of a game as an MVC. Thats a perspective I've never taken (for some odd reason), but definitely an intriguing one that makes a lot of sense. Assuming you do implement your Tetris game with an MVC, I think there are two things you might want to take into account in regards to communication between your controller and your view: There is state, and there are events.
Your controller is obviously the central point of interaction for the user. When they issue keyboard commands, your controller will interpret them, and make the appropriate state adjustments. However, sometimes the game will enter a state that coincides with a particular event...such as filling a line with blocks that should now be removed.
Scoregraphic has given you a great foundation. Your view should operate on a fixed cycle to maintain consistent speed across computers. But in addition to updating the screen to render new state, it should also have a queue of events that it can perform animations in response to. In the case of filling lines in Tetris, your controller could issue strongly typed event objects that derive from some kind of base event type into the view event queue, which could then be used by the view to perform the appropriate animated responses.

Resources