How to make fake Collision in Platform 2D?

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

I tried to make a fake collision in my game but it didn’t work…so after adding gravity in Sprite…it has fallen and stayed at bottom of the platform but instead of being at the bottom of the platform screen…it goes beyond it.so I tried to find out where is the issue. So if anyone can help me to find out my problem…Down below is my code.

extends Node2D
onready var animated_sprite = $AnimatedSprite

var velocity = Vector2.ZERO
var max_run = 100
var run_accel = 800
var gravity = 1000
var max_fall = 160


func _process(delta):
	
	var direction = sign(Input.get_action_strength("ui_right") - Input.get_action_strength("ui_left"))
	
	if direction > 0 :
		animated_sprite.flip_h = false
	elif direction < 0:
		animated_sprite.flip_h = true
	
	if direction != 0:
		animated_sprite.play("Run")
	else:
		animated_sprite.play("Idle")
		
	velocity.x = move_toward(velocity.x, max_run * direction, run_accel * delta)
	velocity.y = move_toward(velocity.y, max_fall, gravity * delta)
	global_position.x += (velocity.x * delta)
	global_position.y += (velocity.y  * delta)
	
	if global_position.y >= 160:
		global_position.y = 160
:bust_in_silhouette: Reply From: TimiT

Solution:

You should use Sprite inside KinematicBody2D because it has method move_and_slide to check collisions automaticully.

Cause:

move_and_slide checks all collisions and builds new movement vector using this data
move_toward only changes position and do not collide

Example:

extends KinematicBody2D

var move= Vector2(0, 0);
const UP= Vector2(0, 1); # it may be important if you want to use is_on_floor() method

func _physics_process(delta):
    move.y += 20;
    move = move_and_slide(move * delta, UP); # it returns Vector2 which show you how character moved

P.S.

Also you can use move_and_collide, but you must to process all collisions it manually

Don’t forget to set CollisionShape2D as child node for platforms and your KinematikBody2D

It may helps:

Thank you!! for your Answer…

Marline | 2021-06-21 16:12