collision between an object with physics and another non-physics object in game maker - physics

//sorry for bad English
I'm using Game maker. I enabled physics for world. I have an object and I don't want to get involved with the physics for this object. So I didn't enabled "use Physics". When I set collision Event between this object and another object(qube), the function didn't acts. If I enable "use Physics" this function will be called. So my question is: "how enable collision between an object with physics and another non-physics object in game maker

In object with physics:
(end step)
x = phy_position_x
y = phy_position_y
In object without physics:
(end step)
if collision_rectangle(bbox_left, bbox_top, bbox_right, bbox_bottom, obj_with_physics, false, true) != noone
{
//collision
}

Related

error with instancing a ball in my pong game in godot

Hello I am working on a pong game in godot. Everything is going well so far but I recieve this error in my debugger:
E 0:01:55.112 body_set_shape_as_one_way_collision: Can't change this state while flushing queries. Use call_deferred() or set_deferred() to change monitoring state instead.
<C++ Error> Condition "body->get_space() && flushing_queries" is true.
<C++ Source> servers/physics_2d/physics_2d_server_sw.cpp:739 # body_set_shape_as_one_way_collision()
AddBall.gd:18 # _on_Area2D_body_entered()
Here is my code for instancing a duplicate ball:
extends Node2D
var collect = false
var ballscene = null
func _ready():
$Area2D/AnimatedSprite.play("Spin")
func _on_Area2D_body_entered(body):
#print(body.name)
if body.name=="Ball"&&collect==false:
collect = true
$Collection.play()
$AnimationPlayer.play("Fade")
$Area2D/AnimatedSprite.stop()
var ball = load("res://Scenes/BallDuplicate.tscn")
ballscene = ball.instance()
find_parent("SpawnManager").get_node("BallDuplicate").add_child(ballscene)
queue_free()
Yes, I instance the ball in the power up and not my spawn manager.
As the error message recommends, you should postpone your node tree changes with call_deffered() as you are not allowed to kick in with adding another rigid bodies to the scene during collision processing.
extends Node2D
var collect = false
var ballscene = null
func CollectFunc():
if not collect:
collect = true
$Collection.play()
$AnimationPlayer.play("Fade")
$Area2D/AnimatedSprite.stop()
var ball = load("res://Scenes/BallDuplicate.tscn")
ballscene = ball.instance()
find_parent("SpawnManager").get_node("BallDuplicate").add_child(ballscene)
queue_free()
func _ready():
$Area2D/AnimatedSprite.play("Spin")
func _on_Area2D_body_entered(body):
#print(body.name)
if body.name=="Ball":
call_deffered("CollectFunc")
Another alternative is to setup your collisions-related signal so that it calls its callback method in "deferred mode".
In the UI, check the "Deferred" box:
Or in GDScript, connect the signal with the "CONNECT_DEFERRED" flag:
$Area2D.connect("body_entered", self, "_on_Area2D_body_entered", [], CONNECT_DEFERRED)

What is this anti-pattern? Invoking a function for a latent effect

Is there a name for this anti-pattern? The best way I can describe it is "invoking a function for a latent effect, not for its primary purpose".
Function A does X and Z
Function B does Y and Z
Function A calls Function B in order to do Z.
Problems with this anti-pattern:
Lack of code expressiveness
Redundant code execution
Cause: Unwillingness to refactor existing code and create a new function
Example:
void afterWifeSaysHello() {
// I need to say "hello!" back to my wife!
// I do the same thing when the doorbell rings so...
afterDoorbellRings();
}
void afterDoorbellRings() {
openDoor();
// pretend that saying hello is more complex than one simple line of code.
say("hello!");
closeDoor();
}
It should be written as:
void afterWifeSaysHello() {
sayHello();
}
void afterDoorbellRings() {
openDoor();
sayHello();
closeDoor();
}
void sayHello() {
say("hello!");
}
Developer A: "You shouldn't call afterDoorbellRings in afterWifeSaysHello because the doorbell didn't ring."
Developer B: "It's just the function name. afterDoorbellRings does what I need."
Developer A: "But you're opening the door for no reason."
Developer B: "The door is still closed in the end so it doesn't matter."
There is a coupling problem in the original afterDoorbellRings method in that it assumes that the "say hello" functionality is only needed in the context of the door opening and closing. The anti-pattern you describe could also happen where the other parts of afterDoorbellRings don't change state, rather than cancel each other out as in your open/close door example. I'm sure this anti-pattern is common enough, but I've never seen it given a name other than "bad coding"!

Communication between objects

If I have Game Class, which has Player object and Board object, Game asks Player what are the coordinates, Player responds, then game checks Board for the coordinates and the result either Hit or Miss.
How can Game forward the result back to Player? so that Player uses the result to set the new coordinates.
I have created code sample below to explain more what i want to do
and also a link to the project here: https://github.com/hythm7/Battleship/tree/master
#!/usr/bin/env perl6
enum Result < Miss Hit >;
class Player {
method fire ( ) {
(^10).pick, (^10).pick
}
}
class Board {
has #.cell = [ +Bool.pick xx ^10 ] xx ^10;
}
class Game {
has Board $.board = Board.new;
has Player $!player = Player.new;
method run ( ) {
loop {
my ($x, $y) = $!player.fire;
if $!board.cell[$y][$x] {
say Hit;
}
else {
say Miss;
}
# How to forward the above result (Hit or Miss) back to the Player object? so
# it can set $y, $x accordingly for the next call to $player.fire
sleep 1;
}
}
}
my $game = Game.new;
$game.run;
Let's see. The main question here is a design one, I think, so let's go for it from this angle. I want to note beforehand that I will describe just a single example of the approach: there are a lot of ways to do it, and I am writing out the simplest I can imagine that works. Also, for the sake of simplicity, code that deals with synchronization, graceful termination and so on is omitted.
Firstly, you have a player to be a separate thing, but in your code it reacts only when it is called from the outside. When it looks like a natural approach when implementing turn-based games, we still want to have some kind of communication. What if a player leaves? What if there is some error condition?
And as you noted the server wants to notify the player about outcome of the game. It seems like we want to have a bi-directional messaging between our Server and Player. Of course, if there is a One Server -> Many Players relation, it is another deal, but we will keep it simple.
Let's prepare some boilerplate code:
# We will get to this `Start` later
enum EventType <Start Hit Miss>;
# A handy class to hold a position, and likely some other data in the future
class Position {
has Int $.x;
has Int $.y;
}
# A board
class Board {
has #.cell = [ +Bool.pick xx ^10 ] xx ^10;
}
Now here is a server:
class Server {
has Board $!board = Board.new;
has Supply $.shots;
has Channel $.player;
method serve {
react {
# Whenever we get a shot coordinates, sent a Hit or Miss to the player
whenever $!shots -> Position $pos {
$!player.send($!board.cell[$pos.y][$pos.x] ?? Hit !! Miss);
# Don't forget to say "I am ready for new events" for the client
$!player.send(Start);
}
# Somebody should start first, and it will be a Server...
$!player.send(Start);
}
}
}
It has a board, and two other attributes - a Supply $.shots and a Channel $.player. If we want to tell something to our player, we are sending a message to the channel. At the same time, we want to know what player wants us to know, so we are listening on everything that comes from our $!shots async stream of values.
The serve method just does our logic - reacts to player's events.
Now to our Player:
class Player {
has Channel $.server;
has Supply $.events;
method play {
react {
whenever $!events {
when Start {
# Here can be user's input
# Simulate answer picking
sleep 1;
$!server.send: Position.new(x => (^10).pick, y => (^10).pick);
# Can be something like:
# my ($x, $y) = get.Int, get.Int;
# $!server.send: Position.new(:$x, :$y);
}
when Hit {
say "I hit that! +1 gold coin!";
}
when Miss {
say "No, that's a miss... -1 bullet!"
}
}
}
}
}
Player has a Channel and a Supply too, as we want a bi-directional relationship. $!server is used to send actions to the server and $!events provides us a stream of events back.
The play method is implemented this way: if the server says that it is ok with our action, we can made our move, if not - we are basically waiting, and when a Hit or Miss event appears, we react to it.
Now we want to tie those two together:
class Game {
has Server $!server;
has Player $!player;
method start {
my $server-to-player = Channel.new;
my $player-to-server = Channel.new;
$!server = Server.new(player => $server-to-player,
shots => $player-to-server.Supply);
$!player = Player.new(server => $player-to-server,
events => $server-to-player.Supply);
start $!server.serve;
sleep 1;
$!player.play;
}
}.new.start;
Firstly, we are creating two channels with self-contained names. Then we create both Server and Player with those channels reversed: player can send to the first one and listen to the second one, server can send to the second one and listen to the first one.
As react is a blocking construct, we cannot run both methods in the same thread, so we start a server in another thread. Then we sleep 1 second to make sure it serves us(that's a hack to avoid negotiation code in this already pretty long answer), and start the player (be it emulation or a real input, you can try both).
Modifying the handlers and the data types sent between Player and Server you can build more complex examples yourself.
One way to do it is to add a Board to the player. If you make it $.board then you get at least a public read accessor which you'll be able to use in the Game class and if you make it is rw you'll get a write accessor so you can just write it.
So, add the Board to Player:
class Player {
has Board $.board is rw = Board.new;
method fire ( ) {
(^10).pick, (^10).pick
}
(And for that to compile you'll need to move the Board class declaration above Player otherwise you'll get a Type 'Board' is not declared error.)
And now you can add a line like this somewhere in the Board class:
$!player.board.cell[$y][$x] = Hit; # or Miss
Also, you need to record one of three states in the cells of the player's board, not two -- Hit, Miss, or unknown. Maybe add Unknown to the enum and initialize the player's board with Unknowns.

Htc Vive + leap motion as controller

I'm trying to implement a feature similar to HTC Vive's controller with the leap motion on my Unity project. I wanted to generate a laser pointer from the index finger and teleport the Vive's room on the position of the laser (as it's done with the controller). The problem is the latest leap motion (orion) documentation, it's unclear. Any ideas how to do that? More in general, we thought about using HandController but we don't understand where to add the script component.
Thanks!
It's unclear to me whether the problem you're having is getting hand data in your scene at all, or using that hand data.
If you're just trying to get hand data in your scene, you can copy a prefab from one of the Unity SDK's example scenes. If you're trying to integrate Leap into an existing scene that already has a VR rig set up, check out the documentation on the core Leap components to understand what pieces need to be in place for you to start getting Hand data. LeapServiceProvider has to be somewhere in your scene to receive hand data.
As long as you have a LeapServiceProvider somewhere, you can access hands from the Leap Motion from any script, anywhere. So for getting a ray from the index fingertip, just pop this script any old place:
using Leap;
using Leap.Unity;
using UnityEngine;
public class IndexRay : MonoBehaviour {
void Update() {
Hand rightHand = Hands.Right;
Vector3 indexTipPosition = rightHand.Fingers[1].TipPosition.ToVector3();
Vector3 indexTipDirection = rightHand.Fingers[1].bones[3].Direction.ToVector3();
// You can try using other bones in the index finger for direction as well;
// bones[3] is the last bone; bones[1] is the bone extending from the knuckle;
// bones[0] is the index metacarpal bone.
Debug.DrawRay(indexTipPosition, indexTipDirection, Color.cyan);
}
}
For what it's worth, the index fingertip direction is probably not going to be stable enough to do what you want. A more reliable strategy is to cast a line from the camera (or a theoretical "shoulder position" at a constant offset from the camera) through the index knuckle bone of the hand:
using Leap;
using Leap.Unity;
using UnityEngine;
public class ProjectiveRay : MonoBehaviour {
// To find an approximate shoulder, let's try 12 cm right, 15 cm down, and 4 cm back relative to the camera.
[Tooltip("An approximation for the shoulder position relative to the VR camera in the camera's (non-scaled) local space.")]
public Vector3 cameraShoulderOffset = new Vector3(0.12F, -0.15F, -0.04F);
public Transform shoulderTransform;
void Update() {
Hand rightHand = Hands.Right;
Vector3 cameraPosition = Camera.main.transform.position;
Vector3 shoulderPosition = cameraPosition + Camera.main.transform.rotation * cameraShoulderOffset;
Vector3 indexKnucklePosition = rightHand.Fingers[1].bones[1].PrevJoint.ToVector3();
Vector3 dirFromShoulder = (indexKnucklePosition - shoulderPosition).normalized;
Debug.DrawRay(indexKnucklePosition, dirFromShoulder, Color.white);
Debug.DrawLine(shoulderPosition, indexKnucklePosition, Color.red);
}
}

Sprite Kit - how do I access child nodes function/IVARs?

I'm working with tile map using Tiled. I have an object on my map for the player spawn point.
I have been able to spawn the player object. However, I'm at a loss as to how to access the player objects functions or IVARs??
In MyScene:
TileMapLayer *_playerLayer = [[TmxTileMapLayer alloc]
initWithTmxObjectGroup:[_tileMap groupNamed:#"Spawn"]
tileSize:_tileMap.tileSize
gridSize:_bgLayer.gridSize
objectType:#"Player"];
[_worldNode addChild:_playerLayer];
This will create a player object. The player object has functions that I want to run and IVARs I want to query. Note, some of the functions return values.
Example from the Player object:
- (BOOL)currentWeaponStatus
{
return _weapon.hidden;
}
So far I think I can access it using:
BOOL weaponHidden = [[_playerLayer childNodeWithName:#"person"] childNodeWithName:#"weapon"].hidden;
But this doesn't seem 'simple'. How do I access the child nodes' functions/IVARs in the _playerLayer?
FYI: I have a weapon node on the player node - this gets added to the tile map layer node.
Thanks for your time.
-Shoes
This is what I needed:
Person *player = (Person *)[_playerLayer childNodeWithName:#"person"];
Thanks to the Chris at Ray Wenderlich...
http://www.raywenderlich.com/forums/viewtopic.php?f=38&t=11775&p=61090#p61090