2D Game colision response - vector

So I am writing a game, but I have come to the part where i need to do some collision response, and I have been stumped. I have an algorithm that finds the objects collision angle, and collision depth meaning how much the two objects over lap. I understand what i want to do and that is to find a perpendicular vector to the collision angle and push back the object that is colliding by it's collision depth, but I just can't seem to write it correctly.
Here is the code I'm working with for the time being.
var collision:Object = collisions[i];
var angle:Number = collision.angle;
var overlap:Number = collision.overlapping.length;
trace(overlap);
trace(angle);
var moveX = Math.cos(angle) * overlap;
var moveY = Math.sin(angle) * overlap;
obj2.x -= moveX;
obj2.y += moveY;
basically I just want the object that is colliding with the wall to stop when it hits it.
any help would be greatly appreciated.

I worked on elastic collision with flash as3 once.I tried to fix overlap a lot of.But i could'nt solved it completely.They did not overlapping normally but if you forced enought, they overlapping.
if you want look at my work, i uploaded my codes.You can download and look at my code.
And if you solve this problem completely, please tell me solution.
swf(with friction, it's more problem) : http://nafiz.in/collision/carpisma.swf
swf(without friction, it's little problem than first.) : http://nafiz.in/collision/carpisma_surtunmesiz.swf
q : add a ball at mouse location.
w, a,s,d : controll #1 ball.
Click with mouse without relase and move mouse and relase. You selected balls.
When you press space, selected balls will go mouse location.
Cods : http://nafiz.in/collision/collision.rar
i hope you solve.

So after a few hours of tweaking the code, I came up with the solution that works well. here is my new code:
public function Colisions(obj1,obj2) {
var collisions:Array=MyCollision.checkCollisions();
for (var i = 0; i < collisions.length; i++) {
var collision:Object=collisions[i];
var angle:Number=collision.angle;
var overlap:Number=collision.overlapping.length;
// finds the amount in x and y coordinates to move the ball back, and it devides overlap by 20 so that the ball does not jump as much.
var moveX=Math.cos(angle)*(overlap/20);
var moveY=Math.sin(angle)*(overlap/20);
// sets the ball to it's original location before the colision.
obj2.x=obj2.x-moveX;
obj2.y=obj2.y-moveY;
}
}
just as a side note I am using CDK which stands for the collision detection toolkit as the algorithm that finds the collisions and the info associated with the collisions.

Related

Alternative to moveWithCollision

I've been making a (potentially massive) multiplayer video game in javascript, nodejs and babylonjs...
It's been a few months that a code is causing me problems in front:
it's currently a simple first person shooter with waves of monsters in player versus player.
The code I'm having trouble with is gravity.
players and monsters can therefore fall or climb, and those from more or less high, of course, the ground is not smooth.
for the moment I calculate the gravity in front only (the server does not receive "y"): I would like not to change that.
The monsters, which can be numerous, are also impacted by gravity only in front.
I searched, went through the babylonjs api and I can't find a viable alternative to "moveWithCollisions"
if (gamers[id][0] == false) {
var before = scene.getMeshByName(gamers[id][1]).gravity.y;
var after = scene.getMeshByName(gamers[id][1]).gravity.y;
for (var a = 0; a < Math.abs(4); a++) {
if (Math.round(after) == Math.round(before)) {
before = scene.getMeshByName(gamers[id][1]).position.y+scene.getMeshByName(gamers[id][1]).gravity.y;
scene.getMeshByName(gamers[id][1]).moveWithCollisions(scene.getMeshByName(gamers[id][1]).gravity);
after = scene.getMeshByName(gamers[id][1]).position.y;
} else {
a = 5;
gamers[id][0] = true;
}
}
when the character receives a move gamers[id][0] becomes false again
I really need a lighter command:
With 100 players and 1000 monsters you will understand that there is no chance that this code will work?
Hence my question, not having the strength to create this command myself, is there a real alternative to the "moveWithCollision" command?
I take you to consider my question, I have been looking for several weeks without finding anything better...
thanks in advance

Move a KinematicBody2D to a known location (godot)

Im making a platformer in godot and in the physics process im getting the players location so I can move the enemy to it(its in the enemy's script but I can not figure out how to move it there im using get_node("/root/World/Player").get_position() to get the location
but when I move and slide towards the player it gives me an error.(btw it is a platformer so it would be nice if the method added gravity)
Invalid type function 'move_and_slide' in base 'KinematicBody2D (enemy.gd)'. Cannot convert argument 2 from float to Vector2.
(It would be nice if the way it
Let us start by looking at the documentation of move_and_slide. This is the signature of the function:
Vector2 move_and_slide ( Vector2 linear_velocity, Vector2 up_direction=Vector2( 0, 0 ), bool stop_on_slope=false, int max_slides=4, float floor_max_angle=0.785398, bool infinite_inertia=true )
Notice:
The first parameter is a velocity vector.
The second parameter is an up vector.
Thus, this function does not work with a position.
And the error you are getting is because you are passing a float on the up parameter.
Why does move_and_slide take an up vector? It is because move_and_slide updates the values you get from is_on_ceiling, is_on_floor and is_on_wall. And how does it know what is a ceiling, a floor or a wall? That's right, it needs to know what way it up. If you let the up vector at ZERO (or just not pass it, since that's the default value), they are all considered walls (and this is OK for a top down game).
Now, you want to do a platformer game, presumably a side scroller. Most likely you want to pass Vector2.UP as second parameter. And that should fix the error.
However, you are sneaking another question in there. One more suited for gamedev.stackexchange.com. You can ask question there (and it does not have to be that you are getting an error).
So, you want to implement a kinematic body with gravity that chases the player. Let us start with the gravity…
The run of the mill code for a kinematic body with gravity looks like this:
extends KinematicBody2D
export(Vector2) var velocity:Vector2
export(float) var gravity:float = 100
func _physics_process(delta:float) -> void:
velocity.y += gravity * delta
velocity = move_and_slide(velocity, Vector2.UP)
Ok, gravity is probably not 100. But that is the basic structure of the code. Note the distance units - being a 2D game - are in pixels, and delta is in seconds. Thus, gravity is in pixels per second squared.
And you want to chase the player avatar. In order to implement that I'll do the following changes:
Have a reference to the player avatar.
Split velocity into vertical and horizontal components.
Have an horizontal speed.
extends KinematicBody2D
export(NodePath) var player_path:NodePath = #"/root/World/Player"
export(float) var horizontal_speed:float = 100
export(float) var gravity:float = 100
onready var player:Node2D = get_node(player_path)
var _velocity:float = 0
func _physics_process(delta:float) -> void:
_velocity.y += gravity * delta
_velocity = move_and_slide(_velocity, Vector2.UP)
var direction_to_player = transform.origin.direction_to(player.transform.origin)
_velocity.x = direction_to_player.x * horizontal_speed
This code uses a NodePath to find the player avatar. Which it queries on ready, and uses that reference from there on. Assuming the player is always there, that is no problem.
The horizontal_speed specifies how fast it moves horizontally towards the player. In pixels per second.
If you don't want it to change velocity while it is in the air, we can do that too:
extends KinematicBody2D
export(NodePath) var player_path:NodePath = #"/root/World/Player"
export(float) var horizontal_speed:float = 100
export(float) var gravity:float = 100
onready var player:Node2D = get_node(player_path)
var _velocity:Vector2 = Vector2.ZERO
func _physics_process(delta:float) -> void:
_velocity.y += gravity * delta
_velocity = move_and_slide(_velocity, Vector2.UP)
if is_on_floor():
var direction_to_player = global_transform.origin.direction_to(player.global_transform.origin)
_velocity.x = direction_to_player.x * horizontal_speed
Notice I'm using global_transform.origin. You could also use global_position. Don't use transform.origin nor position, because they are relative to the parent node. And if the parent is not the same, you are going to get a wrong direction. *I bias towards using transform because
Notice also I'm using is_on_floor after move_and_slide, so I get the updated value. I strongly encourage this pattern: gravity, move_and_slide, decisions.
This is not going to jump or climb ladders or anything like that. It will also get stuck on walls. It has nothing resembling path finding or obstacle avoidance. So, as you can imagine, it can get quite complex depending on what you want to do. However, it grows from there. I know little of the behavior you want to give these kinematic bodies, beyond that you want them to go to the player, using mode_and_slide and with gravity, I have no idea. Thus, I cannot help you further.

Forge 1.16.5 get attack damage of an item

I am trying to get the attack damage of the item in the players offhand. So far I have this mc.player.inventory.offhand.get(0) in my world ticking event (mc is the instance of minecraft). But the item does not seem to have any attack damage attribute. Is there some other way to get it?
I had the same problem, and It took me a while to figure this out. Here's my solution.
Note: I'm using fabric, but this should still work in a similar way with forge.
ItemStack handItem = minecraftClient.player.getMainHandStack();
// get the damage of the item in the players main hand (does not include player base damage)
String itemDamageStr = handItem.getAttributeModifiers(EquipmentSlot.MAINHAND).get(EntityAttributes.GENERIC_ATTACK_DAMAGE).toString().replaceFirst(".*?amount=([0-9]+\\.[0-9]+).*", "$1");
Double itemDamage = 0.0;
if(itemDamageStr.matches("[0-9]+\\.[0-9]+")){
itemDamage = Double.parseDouble(itemDamageStr);
}
// get the players damage
Double playerDamage = minecraftClient.player.getAttributes().getValue(EntityAttributes.GENERIC_ATTACK_DAMAGE);
float totalDamage = (float) (itemDamage + playerDamage);
Also, just in case someone finds this helpful, when I was trying to get the player to damage an entity, I had to grab the entity from the server world in order to do anything to it from the client.
ServerWorld serverWorld = minecraftClient.getServer().getWorld(minecraftClient.world.getRegistryKey());
Entity entity = minecraftClient.targetedEntity;
Entity serverEntity = serverWorld.getEntity(entity.getUuid());

Determining what direction to face over a network with an omnidirectional camera

I have a rather difficult problem. I am making a topdown 2D game. And I have decided to make an omnidirectional character control like realm of the mad god (Video shows at second 16 what that means). I have it all working fine and have managed to work out almost all the kinks of this sort of camera but one thing remains.
(if you dont know what effect im looking create you can see and example hee at 16 seconds mark: https://youtu.be/N2q6aXkvIiI?t=12s)
When the Camera of the the main client gets rotated more that 180 degrees Left becomes right and right becomes left and my messages to the server about flipping the given character when he is supposed to get inverted. I somewhat fixed this by making an if statement that sends an opposite flip request when your world is completely flipped.
However up and down also become a factor as they dont send requests to flip the character.
What im trying to get to is that I have overcomplicted this script I beleive when trying to get the correct messages accross all clients.
I am wondering if anyone has a logical solution to making sure all chracters on the network are always facing the correct direction at all times.
I am using socket.io and Node.js for speaking to the server.
Any input would be appeciated.
TL;DR
How would you go about making realm of the mad gods camera rotation style when all clients need to know what way everyone is facing. (see video 0:16)
thanks.
I have somewhat fixed this problem with a bit of a rewrite of my logic and managed to make all the magic happen on the client and keep the server out of it entirely. I do not know if what I have done is super effecient as I am rather new to coding.
The logic is that I have created a circle collider2D that represents the players field of view. so things slightly outside the camera view are included. Any collision with an object tagged "otherPlayer" will add them to a list.
I then iterate through the list, if its not empty, and I determine if the object is moving away or coming towards me. (thank you to HigherScriptingAuthority for part of the code for this :: https://forum.unity3d.com/threads/left-right-test-function.31420/).
once I know that, all I have to do is grab the transform of that object and flip it accordingly. Boom it now rotates the object or player correctly no matter what rotation the main client is in.
Hope this makes sense and it helps someone:
private float lastDist = 0;
public float dirNum;
void CheckArea()
{
if (listOfPlayers.Count != 0)
{
foreach(var otherPlayer in listOfPlayers)
{
float distance = (transform.position - otherPlayer.transform.position).magnitude;
if (distance < lastDist)
{
Vector3 heading = otherPlayer.transform.position - transform.position;
dirNum = AngleDir(transform.forward, heading, transform.up);
var objectDirection = AngleDir(transform.forward, heading, transform.up);
if (objectDirection > 0)
{
var nav = otherPlayer.GetComponent<Navigator>();
nav.Left();
}
if (objectDirection < 0)
{
var nav = otherPlayer.GetComponent<Navigator>();
nav.Right();
}
}
if (distance > lastDist)
{
Vector3 heading = otherPlayer.transform.position - transform.position;
dirNum = AngleDir(transform.forward, heading, transform.up);
var objectDirection = AngleDir(transform.forward, heading, transform.up);
if (objectDirection > 0)
{
var nav = otherPlayer.GetComponent<Navigator>();
nav.Right();
}
if (objectDirection < 0)
{
var nav = otherPlayer.GetComponent<Navigator>();
nav.Left();
}
}
lastDist = distance;
}
}
}

How to tell if an object has been touch by the player in gml code

Hey am going to give an example of what am trying to do imagine that i have 5 circle sprites and in my gml code i want to do something like this if cirlce_1 was touch then you can touch circle_2 and if circle_2 was touch then you can touch cirlce_3. Please who can help me with this, willing to give a reward via paypal.
Touch events in Game Maker are treated as mouse events. If you want the circles to only allow the player to touch them in order, you can assign each one to have a number and make them all the same object. Take a look at this:
Script to create circles
counter = 0;
lastball = 0;
for(i = 0; i < 10; i++){//Make that third part "i += 1" if using a version before Studio
c = instance_create(floor(random(room_width)), floor(random(room_height)), objCircle);
lastball++;
c.myNum = lastball;
c.radius = 16;//Or whatever radius you want
};
The for statement here automatically generates circles around the room, but if you want manual control, try this:
newCircle()
c = instance_create(argument0, argument1, objCircle);
c.myNum = lastball;
c.radius = 16;
lastball++;
This will create a new circle wherever you want and will automatically increment lastball as well every time it's called. For instance, you could say newCircle(16, 27);.
In the step code for objCircle
if(mouse_check_button_pressed(mb_left) && point_distance(x, y, mouse_x, mouse_y) < radius && counter == myNum){
counter++;//Or counter += 1 in versions before Studio
//Insert whatever circles do when clicked here
};
The circles can be made to do anything when clicked. Since they're all the same object, perhaps you could use a switch statement so each one does something different depending on its number.
Let me know if there's anything else I can help with.

Resources