How to Find Perpendicular Vector in 2D

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By HorseGorilla

Hello! I can’t speak English well, so I hope you understand that I use Google Translator.

There are clockwise and counterclockwise ways to find the perpendicular vector, but I want to make the enemy push vertically differently as shown in the picture. In this case, should I compare the enemy’s position with the player’s position and get all of them separately? For example, using an if statement. help me from your knowledge, thank you.

This is my first question, so I don’t know how to upload a picture. Sorry :slight_smile:

https://photos.app.goo.gl/qHtjY4HCDBYWGqft8

:bust_in_silhouette: Reply From: 1234ab

So if I needed to do this, I would try doing it this way:

  1. get the enemy’s position and the player’s position
    subtract them like this: var vector_from_player_to_enemy = enemy_position - player_position, there may be a built-in way to do this, the idea is to get the vector that points from the player to the enemy
  2. get the angle from the player’s direction to this vector player_direction.angle_to(vector_from_player_to_enemy)
    the sign (+ or -) of the angle will tell if the enemy is on the left or right side of the player
    I am not sure that angle_to can actually return negative angles, but -0.6 is the same (in radians) as 2*PI-0.6, so you may need to check if it is bigger than PI (or convert it to degrees of course if you like that better: var angle_deg = rad2deg(angle_rad)), you should take a look at the values it returns (print() for example) and understand them so you can check for them well
  3. you can then rotate the player’s direction (movement or velocity?) vector by + or - 90° (which are ±PI/2 radians)
    note that the engine uses radians for the angles, so you need radians in here too: var enemy_direction = player_direction.rotated(PI/2)

It was about adding a knockback, but it was smooth. Thank you!

var distance: Vector2 = (owner.position - area.owner.position).normalized()
var degree = excuse_vector.angle_to(distance)
	
    if degree / 90 >= 0:
	    knockback_vector = Vector2(excuse_vector.y, -excuse_vector.x)
    else:
	    knockback_vector = Vector2(-excuse_vector.y, excuse_vector.x)

HorseGorilla | 2021-04-20 02:47