Skip to main content
Known Participant
December 22, 2022
Answered

Setting boundries for "pressmove".

  • December 22, 2022
  • 1 reply
  • 276 views

I want to set the x boundry of an object so it stops dragging between set values. For example, you can drag the object between 50px and 500px.

What code can I add to the following to achieve this?

var root = this;
var Cucumber = root.Cucumber;
createjs.Touch.enable(stage);

Cucumber.on("mousedown", function (e) {
e.currentTarget.offsetX = stage.mouseX / stage.scaleX - e.currentTarget.x;
});

Cucumber.on("pressmove", function (e) {
e.currentTarget.x = stage.mouseX / stage.scaleX - e.currentTarget.offsetX;
});

    This topic has been closed for replies.
    Correct answer Vladin M. Mitov
    var root = this;
    var Cucumber = root.Cucumber;
    createjs.Touch.enable(stage);
    
    var MIN = 50;
    var MAX = 500;
    
    Cucumber.on("mousedown", function (e) {
        e.currentTarget.offsetX = stage.mouseX / stage.scaleX - e.currentTarget.x;
    });
    
    Cucumber.on("pressmove", function (e) {
        var xPos = stage.mouseX / stage.scaleX - e.currentTarget.offsetX;
        e.currentTarget.x = clamp(xPos, MIN, MAX);
    });
    
    function clamp(num, min, max) {
        return Math.min(Math.max(num, min), max);
    }

     

     

    1 reply

    Vladin M. Mitov
    Vladin M. MitovCorrect answer
    Inspiring
    December 22, 2022
    var root = this;
    var Cucumber = root.Cucumber;
    createjs.Touch.enable(stage);
    
    var MIN = 50;
    var MAX = 500;
    
    Cucumber.on("mousedown", function (e) {
        e.currentTarget.offsetX = stage.mouseX / stage.scaleX - e.currentTarget.x;
    });
    
    Cucumber.on("pressmove", function (e) {
        var xPos = stage.mouseX / stage.scaleX - e.currentTarget.offsetX;
        e.currentTarget.x = clamp(xPos, MIN, MAX);
    });
    
    function clamp(num, min, max) {
        return Math.min(Math.max(num, min), max);
    }

     

     

    - Vlad: UX and graphic design, Flash user since 1998Member of Flanimate Power Tools team - extensions for character animation
    Rob_NZAuthor
    Known Participant
    December 22, 2022

    Thanks, that worked perfectly. I'd never heard of "clamp" and after researching it - it's perfect for this code. Thanks for teaching me something new.