How to bounce text using javascript?

38 Views Asked by At

when the text move diagonally if (postiony >= windowHeight - text.offsetHeight || postiony <= 0) {

        if (postiony >= windowHeight - text.offsetHeight) {
            postiony = windowHeight - text.offsetHeight - 1; 
        } else {
            postiony = 1; 
        }
        speed *= -1; 
    }
    if (postionx >= windowWidth - text.offsetWidth || postionx <= 0) {
        
        if (postionx >= windowWidth - text.offsetWidth) {
            postionx = windowWidth - text.offsetWidth - 1; 
            postionx = 1; 
        }
        speed *= -1;  the text just passes though the height a lttle bit , and how to make it bounce in the ooposite direction? like if the inital positon is x=0y=0 it will go diagonal to the down right and it bounces to the make it up right 
1

There are 1 best solutions below

0
ADITYA On

To make text move diagonally within a window and bounce when it reaches the edges. Try this code:

postionx += speed; 
postiony += speed;

// Check if the text has reached the edges of the window
if (postiony >= windowHeight - text.offsetHeight || postiony <= 0) {
    // If the text has reached or passed the bottom edge or the top edge of the window
    if (postiony >= windowHeight - text.offsetHeight) {
        // Adjust position to ensure it stays within the window bounds
        postiony = windowHeight - text.offsetHeight;
    } else {
        postiony = 0; // Assuming you want it to bounce from the top edge
    }
    speed *= -1; // Reverse the direction
}

if (postionx >= windowWidth - text.offsetWidth || postionx <= 0) {
    // If the text has reached or passed the right edge or the left edge of the window
    if (postionx >= windowWidth - text.offsetWidth) {
        // Adjust position to ensure it stays within the window bounds
        postionx = windowWidth - text.offsetWidth;
    } else {
        postionx = 0; // Assuming you want it to bounce from the left edge
    }
    speed *= -1; // Reverse the direction
}