How do I create pressure sensitivity using multiple line segments? (Drawing Program)

Godot Version

v4.2.1

Question

I’m trying to mimic pressure sensitivity by creating multiple line segments. However the program has an issue whereby the segment being drawn can “toggle” the pressure sensitivity as demonstrated in the gif. Any thoughts?

func _input(event: InputEvent) -> void:
                            
    if event is InputEventMouseMotion && _pressed:
        _pressureLast = _pressure
        _pressure = maxf(event.pressure * 10, 1)
        _pressureDiff = abs(_pressureLast - _pressure)
                
        if (_pressureDiff > 0.25):
            _current_line = Line2D.new()                
            draw_line(_mousePositionLast, _mousePosition, Color.BLACK, _pressure, false)
            add_child(_current_line)
        
        _mousePositionLast = _mousePosition        
        _mousePosition = event.position
        _current_line.add_point(event.position)                
        _current_line.set_width(_pressure)
    
    if event is InputEventMouseButton:
            _pressed = event.pressed
            if _pressed:
                _current_line = Line2D.new()        
                add_child(_current_line)

TabletDiffereingPressures2

Hey!

There are multiple noteworthy things going on there.

First the draw_line call is actually inert and does nothing, what you have displayed is only your add_child(_current_line)

Moreover I think that any draw call should be placed in a _draw() builtin overload

Also you are maxing your pressure to 1 when the default value of this field is 10, might be another thing to dig.

But cut to the chase, I found something that sort of worked:

extends Node2D

var _pressed: bool = false
var _current_line: Line2D = null

var _mousePosition: Vector2 = Vector2()
var _mousePositionLast: Vector2 = Vector2()

var _pressure: float = 0
var _pressureLast: float = 1
var _pressureDiff: float = 0

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion && _pressed:
		_pressureLast = _pressure
		_mousePositionLast = _mousePosition
		_mousePosition = event.position

		# I don't have pressure sensitive hardware, so I'm faking it
		_pressure = randf_range(1, 10)

		_pressureDiff = abs(_pressureLast - _pressure)

		# Create a new line segment if the pressure difference is greater than 0.25
		if (_pressureDiff > 0.25):
			var previous_line : Line2D = _current_line

			_current_line = Line2D.new()
			if previous_line != null:
				# Make the link between the previous line and the new line
				_current_line.add_point(_mousePositionLast)

			add_child(_current_line)

		_current_line.add_point(_mousePosition)                
		_current_line.set_width(_pressure)

	if event is InputEventMouseButton:
			_pressed = event.pressed
			if _pressed == false:
				_current_line = null

I hope that helped!