For some reason, the enemy, when following the player, can change the path for a second to some corner or somewhere else. Because of this, he sometimes twitches and goes back. What could be the problem? Here is my code
extends CharacterBody2D
class_name Ghosts
#onready var region_id: RID = NavigationServer2D.region_create()
var path:Array = []
var nav:NavigationRegion2D = null
var player = null
func _ready():
await get_tree()
var tree = get_tree()
if tree.has_group("LevelNavigation"):
nav = tree.get_nodes_in_group("LevelNavigation")[0]
NavigationServer2D.region_set_map(region_id, get_world_2d().navigation_map)
NavigationServer2D.region_ser_navpoly(region_id, nav.navpoly)
if tree.has_group("Player"):
player = tree.get_nodes_in_group("Player")[0]
func attack(speed:int):
if path.size() > 0:
velocity = global_position.direction_to(path[1]) * speed
if global_position == path[0]:
path.pop_front()
move_and_slide()
func generate_path(line2D: Line2D):
if nav != null and player != null:
path = NavigationServer2D.map_get_path(get_world_2d().navigation_map, position
line2D.points = path
I would like to get the correct path. Maybe it's the features of Godot 4
Noop
First this is nothing:
await get_tree()
The method get_tree is not asynchronous, and you are discarding the result anyway. Perhaps you wanted to await for the Node to enter the scene tree? That would be await self.tree_entered… Except you have the line inside _ready and when Godot calls _ready the Node is inside the tree (which also means it will not enter, so waiting for it to enter won't work).
Just remove that line.
Following the path
Second this won't work well:
if path.size() > 0:
velocity = global_position.direction_to(path[1]) * speed
if global_position == path[0]:
path.pop_front()
move_and_slide()
You are moving towards path[1] and not path[0]
Even if you were, nothing is preventing you from overshooting.
Even if you were preventing overshooting, the equality comparison won't work well due to floating point errors.
So the plan:
If there are no points in the path, we are done.
If there are points in the path, pick the first point.
If the current position is close enough to the point, remove it.
Otherwise move towards the point.
Let us do it:
if path.empty():
return
var point := path[0]
if global_position.distance_to(point) <= threshold:
path.pop_front()
return
velocity = global_position.direction_to(point) * speed
move_and_slide()
Ok, caveats:
We need to prevent overshooting.
How much is the threshold?
When we remove we don't move.
Let us fix that. We need to figure out, beforehand, much we have to move:
var distance_to_move := speed * delta
But we should not advance more than the distance to the point!
if path.empty():
return
var point:Vector2 = path[0]
var distance_to_point := global_position.distance_to(point)
var distance_to_move := min(speed * delta, distance_to_point)
And the velocity will be that to move that in this frame:
if path.empty():
return
var point:Vector2 = path[0]
var distance_to_point := global_position.distance_to(point)
var direction_to_point := global_position.direction_to(point)
var distance_to_move := minf(speed * delta, distance_to_point)
if distance_to_point <= distance_to_move:
path.pop_front()
velocity = direction_to_point * (distance_to_move / delta)
move_and_slide()
This way we don't overshoot, we move even when we remove, and we have a clear threshold for removing.
Caveats:
We don't always move the full distance.
For that we need a loop:
var total_distance_to_move := speed * delta
while total_distance_to_move > 0.0 and not path.empty():
var point:Vector2 = path[0]
var distance_to_point := global_position.distance_to(point)
var direction_to_point := global_position.direction_to(point)
var distance_to_move := minf(total_distance_to_move, distance_to_point)
if distance_to_point <= distance_to_move:
path.pop_front()
velocity = direction_to_point * (distance_to_move / delta)
move_and_slide()
total_distance_to_move -= distance_to_move
Generating the path
The code is cut off where you use map_get_path, however I can see you are using position.
Work with the global_position instead:
path = Navigation2DServer.map_get_path(
get_world_2d().get_navigation_map(),
global_position,
target_pos,
true
)
I don't know how you were getting the target position, but I'll trust you can figure out how to make it with global coordinates.
And you are setting this to a Line2D. That wants its own local coordinantes. So you do this:
line2d.points = line2d.global_transform.affine_inverse() * path
Related
I'm making my first mobile game on godot so I'm very inexperienced. It is a platformer. I would like the player, when he collides with the enemy, to fall down and die. I've been trying to do it for days, but it always gives me some different problem and I don't understand what I'm doing wrong. Could anyone help me please? I leave you the player code; in this way the player, despite having set velocity.y=.500, does not fall, but makes a sort of jump. What's wrong? Thank you all in advance.
PLAYER CODE:
extends KinematicBody2D
onready var rayS = get_node("rayL")
onready var rayD = get_node("rayR")
onready var sprite = get_node("AnimatedSprite")
var alive = true
signal dead
const WALK_FORCE = 600
const WALK_MAX_SPEED = 300
const STOP_FORCE = 1300
const JUMP_SPEED = 700
const gravity = 1100.0
var velocity = Vector2()
func _physics_process(delta):
var force = Vector2(0, gravity)
var walk_left = Input.is_action_pressed("move_left") and alive
var walk_right = Input.is_action_pressed("move_right") and alive
var jump = Input.is_action_pressed("jump") and alive
# Horizontal movement code. First, get the player's input.
var walk = WALK_FORCE * (Input.get_action_strength("move_right") - Input.get_action_strength("move_left"))
# Slow down the player if they're not trying to move.
if abs(walk) < WALK_FORCE * 0.2:
# The velocity, slowed down a bit, and then reassigned.
velocity.x = move_toward(velocity.x, 0, STOP_FORCE * delta)
else:
velocity.x += walk * delta
# Clamp to the maximum horizontal movement speed.
velocity.x = clamp(velocity.x, -WALK_MAX_SPEED, WALK_MAX_SPEED)
# Vertical movement code. Apply gravity.
velocity.y += gravity * delta
# Move based on the velocity and snap to the ground.
velocity = move_and_slide_with_snap(velocity, Vector2.DOWN, Vector2.UP)
# Check for jumping. is_on_floor() must be called after movement code.
if is_on_floor() and Input.is_action_just_pressed("jump"):
jumping()
var on_floor = rayL.is_colliding() or rayR.is_colliding()
if walk_right:
sprite.set_flip_h(false)
if walk_left:
sprite.set_flip_h(true)
if (walk_left or walk_right) and on_floor:
sprite.play()
elif (walk_left or walk_right):
sprite.stop()
sprite.set_frame(3)
else:
sprite.stop()
sprite.set_frame(1)
if position.y > 900: dying()
func _on_Area2D_body_entered(body):
if not alive: return
jumping()
body.destroy()
func jumping():
velocity.y = -JUMP_SPEED
func _on_Area2D2_body_entered(body):
if not alive: return
dying()
func dying():
if not alive: return
alive = false
velocity.y = -500
collision_mask -= 2
emit_signal("dead")
In 2D, moving UP direction is negative on the y axis. Said another way, the Y axis is pointing downwards.
Thus, setting the velocity like this:
velocity.y = -500
Will result in upward motion, not downwards.
I am making a space game in Godot and whenever my ship is a big distance away from (0,0,0) every time I move the camera or the ship, it shakes violently. Here is my code for moving the ship:
extends KinematicBody
export var default_speed = 500000
export var max_speed = 5000
export var acceleration = 100
export var pitch_speed = 1.5
export var roll_speed = 1.9
export var yaw_speed = 1.25
export var input_response = 8.0
var velocity = Vector3.ZERO
var forward_speed = 0
var vert_speed = 0
var pitch_input = 0
var roll_input = 0
var yaw_input = 0
var alt_input = 0
var system = "System1"
func _ready():
look_at(get_parent().get_node("Star").translation, Vector3.UP)
func get_input(delta):
if Input.is_action_pressed("boost"):
max_speed = 299792458
acceleration = 100
else:
max_speed = default_speed
acceleration = 100
if Input.is_action_pressed("throttle_up"):
forward_speed = lerp(forward_speed, max_speed, acceleration * delta)
if Input.is_action_pressed("throttle_down"):
forward_speed = lerp(forward_speed, 0, acceleration * delta)
pitch_input = lerp(pitch_input, Input.get_action_strength("pitch_up") - Input.get_action_strength("pitch_down"), input_response * delta)
roll_input = lerp(roll_input, Input.get_action_strength("roll_left") - Input.get_action_strength("roll_right"), input_response * delta)
yaw_input = lerp(yaw_input, Input.get_action_strength("yaw_left") - Input.get_action_strength("yaw_right"), input_response * delta)
func _physics_process(delta):
get_input(delta)
transform.basis = transform.basis.rotated(transform.basis.z, roll_input * roll_speed * delta)
transform.basis = transform.basis.rotated(transform.basis.x, pitch_input * pitch_speed * delta)
transform.basis = transform.basis.rotated(transform.basis.y, yaw_input * yaw_speed * delta)
transform.basis = transform.basis.orthonormalized()
velocity = -transform.basis.z * forward_speed * delta
move_and_collide(velocity * delta)
func _on_System1_area_entered(area):
print(area, area.name)
system = "E"
func _on_System2_area_entered(area):
print(area, area.name)
system = "System1"
Is there any way to prevent this from happening?
First of all, I want to point out, that this is not a problem unique to Godot. Although other engines have automatic fixes for it.
This happens because the precision of floating point numbers decreases as it goes away form the origin. In other words, the gap between one floating number and the next becomes wider.
The issue is covered in more detail over the game development sister site:
Why loss of floating point precision makes rendered objects vibrate?
Why does the resolution of floating point numbers decrease further from an origin?
What's the largest "relative" level I can make using float?
Why would a bigger game move the gameworld around the Player instead of just moving a player within a gameworld?
Moving player inside of moving spaceship?
Spatial Jitter problem in large unity project
Godot uses single precision. Support for double precision has been added in Godot 4, but that just reduces the problem, it does not eliminate it.
The general solution is to warp everything, in such way that the player is near the origin again. So, let us do that.
We will need a reference to the node we want to keep near the origin. I'm going to assume which node it is does not change during game play.
export var target_node_path:NodePath
onready var _target_node:Spatial = get_node(target_node_path)
And we will need a reference to the world we need to move. I'm also assuming it does not change. Furthermore, I'm also assuming the node we want to keep near the origin is a child of it, directly or indirectly.
export var world_node_path:NodePath
onready var _world_node:Node = get_node(target_node_path)
And we need a maximum distance at which we perform the shift:
export var max_distance_from_origin:float = 10000.0
We will not move the world itself, but its children.
func _process() -> void:
var target_origin := _target_node.global_transform.origin
if target_origin.length() < max_distance_from_origin:
return
for child in _world_node.get_children():
var spatial := child as Spatial
if spatial != null:
spatial.global_translate(-target_origin)
Now, something I have not seen discussed is what happens with physics objects. The concern is that The physics server might be trying to move them in the old position (in practice this is only a problem with RigidBody), and it will overwrite what we did.
So, if that is a problem… We can handle physic objects with a teleport. For example:
func _process() -> void:
var target_origin := _target_node.global_transform.origin
if target_origin.length() < max_distance_from_origin:
return
for child in _world_node.get_children():
var spatial := child as Spatial
if spatial != null:
var body_transform := physics_body.global_transform
var new_transform := Transform(
body_transform.basis,
body_transform.origin - target_origin
)
spatial.global_transform = new_transform
var physics_body := spatial as PhysicsBody # Check for RigidBody instead?
if physics_body != null:
PhysicsServer.body_set_state(
physics_body.get_rid(),
PhysicsServer.BODY_STATE_TRANSFORM,
new_transform
)
But be aware that the above code does not consider any physics objects deeper in the scene tree.
In my game I want it so when either the player or the enemy gets damaged they bounce but i do not know how to do so.
code for player:
extends KinematicBody2D
var speed = 200 # speed in pixels/sec
var velocity = Vector2.ZERO
var hasDagger = false
func get_input():
velocity = Vector2.ZERO
if Input.is_action_pressed('right'):
velocity.x += 1
if Input.is_action_pressed('left'):
velocity.x -= 1
if Input.is_action_pressed('down'):
velocity.y += 1
if Input.is_action_pressed('up'):
velocity.y -= 1
if Input.is_action_just_pressed("sprint"):
speed += 100
if Input.is_action_just_released("sprint"):
speed -= 100
# Make sure diagonal movement isn't faster
velocity = velocity.normalized() * speed
func _physics_process(delta):
get_input()
velocity = move_and_slide(velocity)
enemy code:
extends KinematicBody2D
var run_speed = 201
var velocity = Vector2.ZERO
var collider = null
var health = 3
func _physics_process(delta):
velocity = Vector2.ZERO
if collider:
#print(collider)
velocity = global_position.direction_to(collider.global_position) * run_speed
velocity = move_and_slide(velocity)
func _on_DetectRadius_body_entered(body):
collider = body
func _on_DetectRadius_body_exited(body):
collider = null
func _on_hit_box_body_entered(body):
health -= 1
if health == 0:
get_tree().change_scene("res://scenes/game over.tscn")
the health you see in the enemy script is for the player
the player is a kinematicbody2D with a colilistionshape2D and the enemy is the same as that
What I'm going to show is not the only way to go about this - In fact, we should be talking about animations and states - instead it is just one way to tackle this.
I'll define a variable target. I'll leave it without specifying a type, so it is variant. However, I'll have it be Vector2. The reason I leave it variant, is so it can be null. If I could, I'd type it as a nullable Vector2, but Godot does not support that.
The idea is to have the KinematicBody2D go to the target position if it is a Vector2. But if it isn't, let the regular movement continue. Something like this:
export var speed:float
var velocity := Vector2.ZERO
var target = null
func _physics_process(_delta:float) -> void:
if target != null:
velocity = global_position.direction_to(target) * speed
else:
# call get_input or whatever
pass
velocity = move_and_slide(velocity)
I'll add a method for this, it will make things easier:
export var speed:float
var velocity := Vector2.ZERO
var target = null
func _physics_process(_delta:float) -> void:
if not advance_to_target():
# call get_input or whatever
pass
velocity = move_and_slide(velocity)
func advance_to_target() -> bool:
if target == null:
return false
velocity = global_position.direction_to(target) * speed
return true
Well, we should clear target when we reach it, and we should not overshoot. Let us fix that:
export var speed:float
var velocity := Vector2.ZERO
var target = null
func _physics_process(_delta:float) -> void:
if not advance_to_target():
target = null
# call get_input or whatever
velocity = move_and_slide(velocity)
func advance_to_target() -> bool:
if target == null:
return false
var displacement := target - global_position
var distance := displacement.length()
if is_zero_approx(distance):
return false
var time := get_physics_process_delta_time()
var max_speed := distance / time
var direction := displacement / distance
velocity = direction * min(speed, max_speed)
return true
Here we are computing max_speed, which is the speed at which the KinematicBody2D would have to move to reach the target in the current physics frame. Any faster than that, and it would overshoot. So we use min(speed, max_speed) to make sure the actual speed is capped at that.
And when the target is reached we would have found that the distance is zero. Well, almost zero. Because of rounding errors we cannot rely on it hitting zero exactly. That is why I use is_zero_approx(distance). This also avoids a division by zero at displacement / distance.
For the enemy we can co-opt this system to chase the collider… Let us refactor to make that easier:
export var speed:float
var velocity := Vector2.ZERO
var target = null
var collider = null
func _physics_process(_delta:float) -> void:
var target_position = null
if target != null:
target_position = target
elif collider != null:
target_position = collider.global_position
if not advance_to(target_position):
target = null
velocity = move_and_slide(velocity)
func advance_to(target_position) -> bool:
if target_position == null:
return false
var displacement := position - global_position
var distance := displacement.length()
if is_zero_approx(distance):
return false
var time := get_physics_process_delta_time()
var max_speed := distance / time
var direction := displacement / distance
velocity = direction * min(speed, max_speed)
return true
Or we can add get_input into it:
export var speed:float
var velocity := Vector2.ZERO
var target = null
func _physics_process(_delta:float) -> void:
if not advance_to(target):
target = null
get_input()
velocity = move_and_slide(velocity)
func advance_to(target_position) -> bool:
if target_position == null:
return false
var displacement := position - global_position
var distance := displacement.length()
if is_zero_approx(distance):
return false
var time := get_physics_process_delta_time()
var max_speed := distance / time
var direction := displacement / distance
velocity = direction * min(speed, max_speed)
return true
func get_input():
velocity = Vector2.ZERO
if Input.is_action_pressed('right'):
velocity.x += 1
if Input.is_action_pressed('left'):
velocity.x -= 1
if Input.is_action_pressed('down'):
velocity.y += 1
if Input.is_action_pressed('up'):
velocity.y -= 1
if Input.is_action_just_pressed("sprint"):
speed += 100
if Input.is_action_just_released("sprint"):
speed -= 100
# Make sure diagonal movement isn't faster
velocity = velocity.normalized() * speed
Ah, yes, the damage. We are going to set a target when we register the collision. Something like this:
export var push_back_distance:float
func _on_hit_box_body_entered(body):
var direction := global_position.direction_to(body.global_position)
target = global_position - direction * push_back_distance
# the rest of the code here
That should make the KinematicBody2D move away from whatever it collided with.
I'm trying to create a "Block" input that summons a wall at the position the camera is looking at and have it face the camera's direction. It seems to be using the global coordinates which doesn't make sense to me, because I use the same code to spawn a bullet with no problem. Here's my code:
if Input.is_action_just_pressed("light_attack"):
var b = bullet.instance()
muzzle.add_child(b)
b.look_at(aimcast.get_collision_point(), Vector3.UP)
b.shoot = true
print(aimcast.get_collision_point())
if Input.is_action_just_pressed("block"):
var w = wall.instance()
w.look_at(aimcast.get_collision_point(),Vector3.UP)
muzzle.add_child(w)
w.summon = true
The light attack input is the code used to summon and position the bullet. muzzle is the spawn location (just a spatial node at the end of the gun) and aimcast is a raycast from the center of the camera. All of this is run in a get_input() function. The wall spawns fine, I just can't orient it. I also need to prevent any rotation on the y-axis. This question is kinda hard to ask, so I couldn't google it. If you need any clarification please let me know.
New Answer
The asked comment made me realize there is a simpler way. In the old answer I was defining a xz_aim_transform, which could be done like this:
func xz_aim_transform(pos:Vector3, target:Vector3) -> Transform:
var alt_target := Vector3(target.x, pos.y, target.z)
return Transform.IDENTITY.translated(pos).looking_at(alt_target, Vector3.UP)
That is: make a fake target at the same y value, so that the rotation is always on the same plane.
It accomplishes the same thing as the approach in the old answer. However, it is shorter and easier to grasp. Regardless, I generalized the approach in the old answer, and the explanation still has value, so I'm keeping it.
Old Answer
If I understand correctly, you want something like look_at except it only works on the xz plane.
Before we do that, let us establish that look_at is equivalent to this:
func my_look_at(target:Vector3, up:Vector3):
global_transform = global_transform.looking_at(target, up)
The take away of that is that it sets the global_transform. We don't need to delve any deeper in how look_at works. Instead, let us work on our new version.
We know that we want the xz plane. Sticking to that will make it simpler. And it also means we don't need/it makes no sense to keep the up vector. So, let us get rid of that.
func my_look_at(target:Vector3):
# global_transform = ?
pass
The plan is to create a new global transform, except it is rotated by the correct angle around the y axis. We will figure out the rotation later. For now, let us focus on the angle.
Figuring out the angle will be easy in 2D. Let us build some Vector2:
func my_look_at(target:Vector3):
var position := global_transform.origin
var position_2D := Vector2(position.x, position.z)
var target_2D := Vector2(target.x, target.z)
var angle:float # = ?
# global_transform = ?
That part would not have been as easy with an arbitrary up vector.
Notice that we are using the 2D y for the 3D z values.
Now, we compute the angle:
func my_look_at(target:Vector3):
var position := global_transform.origin
var position_2D := Vector2(position.x, position.z)
var target_2D := Vector2(target.x, target.z)
var angle := (target_2D - position_2D).angle_to(Vector2(0.0, -1.0))
# global_transform = ?
Since we are using the 2D y for the 3D z values, Vector2(0.0, -1.0) (which is the same as Vector2.UP, by the way) is representing Vector3(0.0, 0.0, -1.0) (Which is Vector3.FORWARD). So, we are computing the angle to the 3D forward vector, on the xz plane.
Now, to create the new global transform, we will first create a new basis from that rotation, and use it to create the transform:
func my_look_at(target:Vector3):
var position := global_transform.origin
var position_2D := Vector2(position.x, position.z)
var target_2D := Vector2(target.x, target.z)
var angle := (target_2D - position_2D).angle_to(Vector2.UP)
var basis := Basis(Vector3.UP, angle)
global_transform = Transform(basis, position)
You might wonder why we don't use global_transform.rotated, the reason is that using that multiple times would accumulate the rotation. It might be ok if you only call this once per object, but I rather do it right.
There is one caveat to the method above. We are losing any scaling. This is how we fix that:
func my_look_at(target:Vector3):
var position := global_transform.origin
var position_2D := Vector2(position.x, position.z)
var target_2D := Vector2(target.x, target.z)
var angle := (target_2D - position_2D).angle_to(Vector2.UP)
var basis := Basis(Vector3.UP, angle).scaled(global_transform.basis.get_scale())
global_transform = Transform(basis, position)
And there you go. That is a custom "look at" function that works on the xz plane.
Oh, and yes, as you have seen, your code works with global coordinates. In fact, get_collision_point is in global coordinates.
Thus, I advice not adding your projectiles as children. Remember that when the parent moves, the children move with it, because they are placed relative to it.
Instead give them the same global_transform, and then add them to the scene tree. If you add them to the scene before giving them their position, they might trigger a collision.
You could, for example, add them directly as children to the root (or have a node dedicated to holding projectiles, another common option is to add them to owner).
That way you are doing everything on global coordinates, and there should be no trouble.
Well, since you are going to set the global_transform anyway, how about this:
func xz_aim_transform(position:Vector3, target:Vector3) -> Transform:
var position_2D := Vector2(position.x, position.z)
var target_2D := Vector2(target.x, target.z)
var angle := (target_2D - position_2D).angle_to(Vector2.UP)
var basis := Basis(Vector3.UP, angle)
return Transform(basis, position)
Then you can do this:
var x = whatever.instance()
var position := muzzle.global_transform.origin
var target := aimcast.get_collision_point()
x.global_transform = xz_aim_transform(position, target)
get_tree().get_root().add_child(x)
x.something = true
print(target)
By the way, this would be the counterpart of xz_aim_transform not constrained to the xz plane:
func aim_transform(position:Vector3, target:Vector3, up:Vector3) -> Transform:
return Transform.IDENTITY.translated(position).looking_at(target, up)
It took me some ingenuity, but here is the version constrained to an arbitrary plane (kind of, as you can see it does not handle all cases):
func plane_aim_transform(position:Vector3, target:Vector3, normal:Vector3) -> Transform:
normal = normal.normalized()
var forward_on_plane := Vector3.FORWARD - Vector3.FORWARD.project(normal)
if forward_on_plane.length() == 0:
return Transform.IDENTITY
var position_on_plane := position - position.project(normal)
var target_on_plane := target - target.project(normal)
var v := forward_on_plane.normalized()
var u := v.rotated(normal, TAU/4.0)
var forward_2D := Vector2(0.0, forward_on_plane.length())
var position_2D := Vector2(position_on_plane.project(u).dot(u), position_on_plane.project(v).dot(v))
var target_2D := Vector2(target_on_plane.project(u).dot(u), target_on_plane.project(v).dot(v))
var angle := (target_2D - position_2D).angle_to(forward_2D)
var basis := Basis(normal, angle)
return Transform(basis, position)
Here w - w.project(normal) gives you a vector perpendicular to the normal. And w.project(u).dot(u) gives you how many times u fit in w, signed. So we use that build our 2D vectors.
I want to position x,y,z labels (sprites) on the axis I have in my scene. The problem is that zooming with the camera , should result to also moving the particles analogously so they stay in the side of the "screen".
So I just want to find a way to always know where the lines of x,y,z are out of the camera to update the labels' positions :
fiddle (here they are just static).
the pseudocode of what I might need to acheve that :
function update() {
var pointInLinePosition = calculateLastVisiblePointOfXline();
xSprite.position.set(pointInLinePosition.x, pointInLinePosition.y, pointInLinePosition.z);
}
function calculateLastVisiblePointOfXline(){
}
I found a solution which is satisfying enough (for me at least) but not perfect.
Firstly I create a frustum using the scene's camera :
var frustum = new THREE.Frustum();
frustum.setFromMatrix( new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse ) );
Then, I check if any of the planes of the frustum intersects with any of the lines I have in the scene :
for (var i = frustum.planes.length - 1; i >= 0; i--) {
var py = frustum.planes[i].intersectLine( new THREE.Line3( new THREE.Vector3(0,0,0), new THREE.Vector3(1000,0,0) ) ) ;
if(py !== undefined) {
ySprite.position.x = py.x-1 ;
}
var px = frustum.planes[i].intersectLine( new THREE.Line3( new THREE.Vector3(0,0,0), new THREE.Vector3(0,0,1000) ) ) ;
if(px !== undefined) {
xSprite.position.z = px.z-1 ;
}
};
If there is an intersection, I update the labels' position using the return value of the intersectLine() which is the point of intersection.
This is the updated fiddle : fiddle
I hope that helps. In my case it fit.
A correct test for intersections also has to make sure that the intersection point is actually within the frustum as the frustum planes extend indefinitely, potentially leading to false positive intersections.
One naive way of validating intersections, is checking the distance of the intersection to all planes. If the distance is greater or equal to zero, the point is within the frustum.
Adjusted code snipped from ThanosSar's answer:
const intersect = point => frustum.planes
.map(plane =>
plane.intersectLine(new THREE.Line3(new THREE.Vector3(0, 0, 0), point))
)
.filter(sect => sect != null)
.filter(sect => frustum.planes.every(plane => plane.distanceToPoint(sect) >= -0.000001))[0];
const iy = intersect(new THREE.Vector3(1000, 0, 0));
if (iy != null)
ySprite.position.x = iy.x - 1;
const ix = intersect(new THREE.Vector3(0, 0, 1000));
if (ix != null)
xSprite.position.z = ix.z - 1;
(The comparison is with >= -0.000001 to account for floating point rounding errors)
Fiddle