# Problem with mouseMoved function

**URL:** https://discourse.processing.org/t/problem-with-mousemoved-function/2101
**Category:** Processing
**Created:** [July 26, 2018, 3:12pm UTC](https://discourse.processing.org/t/problem-with-mousemoved-function/2101 "2018-07-26T15:12:49Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![puddle](https://avatars.discourse-cdn.com/v4/letter/p/57b2e6/32.png) [@puddle](https://discourse.processing.org/u/puddle)
#### Post date: [July 26, 2018, 3:12pm UTC](https://discourse.processing.org/t/problem-with-mousemoved-function/2101/1 "2018-07-26T15:12:49Z")

</div>

I’m trying to create a 3D pong game in pocessing and one of my paddles is supposed to move with the mouse, but instead of just that paddle moving woth the mouse everything is. I pasted my code down below. Any help would be apreciated.

**PONG PROJECT**

from p1 import Paddle1  
from p2 import p2  
from ball import Ball

def setup():  
#1. set the size of your screen  
size(800, 600, P3D)

```
global img
#2. load an image, store it in img, and resize it to the size of your screen\
img = loadImage("box.img.jpg")
img.resize(800, 600)
global p1
#3. make a paddle on the left side of the screen and store it in p1
p1 = Paddle1((50, 50), 20, 100, 50, 50, "p1")
global p2
#4. make a paddle on the left side of the screen and store it in p2
p2 = p2((50, 50), 20, 100, 50, 700, "p2")
global ball
#5. make a Ball that starts at the center of your screen and store it in ball.
# Also pass in the paddles!!
ball = Ball(400, 300, 25, 25, 12.5, p1, p2)
global score1
#6a. Store an integer 0 in score1
score1 = 0
global score2
#6b. Store an integer 0 in score2
score2 = 0

```

def draw():  
global p1, p2, ball, score1, score2, img  
background(img)  
#7. call update() for p1, p2, ball  
p1.update()  
p2.update()  
ball.update()  
#8. call updateScore()  
updateScore()  
textAlign(LEFT, TOP)  
textSize(40)  
fill(255, 255, 255)  
#9. copy the following line but replace score1 with score2, and move the x/y  
# coords to the right side of your screen  
text(str(score1), 25, 0)  
text(str(score2), 750, 0)

```
#10. Use if-statements and check the location of p1 and mouseY so that the paddle
# will move up if the mouse is above it, and will move down if the mouse is below it

```

def mouseMoved():  
if p1.y \>= mouseY:  
p1.moveUp(3)  
elif p1.y \<= mouseY:  
p1.moveDown(3)

def keyPressed():  
#11. Use if-statements and check if keyCode is UP or if the keyCode is DOWN so that p2  
# will move up if UP is pressed, and p2 will move down if DOWN is pressed  
#  
if keyCode == UP:  
p2.moveUp(10)  
elif keyCode == DOWN:  
p2.moveDown(10)

#updateScore: checks if the score needs to be updated. If it does, update it accordingly and

# reset the ball to the middle of the screen

#input: none  
#output: none  
def updateScore():  
global ball, score1, score2

```
#12. write a if-statement that will check the location of the ball. If it touches/moves
# past the left edge of the screen, update score2. If it touches/moves past the right
# side of the screen, update score1 accordingly
# if the ball touches EITHER edge, call: ball.reset(width / 2, height / 2)
if ball.ballLeft() <= 0 or ball.ballRight() >= width:
    if ball.ballLeft() <= 0:
        score2 += 1
    elif ball.ballRight() >= width:
        score1 += 1
    ball.reset(width / 2, height / 2) 

```

**ball.py**  
#A class for a ball in pong  
import collisionDetection as cd  
class Ball:

```
# __init__ : creates a ball
# input: x, the starting x-coordinate of the ball
# y, the starting y-coordinate of the ball
# w, the starting width of the ball
# h, the starting height of the ball
# leftPaddle, the paddle on the left
# rightPaddle, the paddle on the right
def __init__ (self, x, y, w, h, r, leftPaddle, rightPaddle):
    #1. store all of the inputs in instance variables!
    self.x = x
    self.y = y
    self.r = r
    self.w = w
    self.h = h

    self.leftPaddle = leftPaddle
    self.rightPaddle = rightPaddle
    
    #Initialize the change of x and y coordinates at the beginning of the game
    self.dx = 2
    self.dy = 2

#ballRight: helper method for returning the x coordinate of right edge of the ball
#input: none
#output: the x-coordinate of the right edge of the ball
def ballRight(self):
    #2. write this function
    return self.x + (self.w / 2)

#ballLeft: helper method for returning the x coordinate of left edge of the ball
#input: none
#output: the x-coordinate of the left edge of the ball
def ballLeft(self):
    #3. write this function
    return self.x - (self.w / 2)

#ballUpY: helper method for returning the y coordnate of the upper edge of the ball
#input: none
#output: the y-coordinate of the upper edge of the ball
def ballUpY(self):
    #4. write this function
    return self.y - (self.h / 2)

#ballDownY: helper method for returning the y coordnate of the lower edge of the ball
#input: none
#output: the y-coordinate of the lower edge of the ball
def ballDownY(self):
    #5. write this function
    return self.y + (self.h / 2)

#isTouchingEdge: checks if the ball is touching either of the vertical edges  
#input: none
#output: True if the ball is touching the upper or lower edge, false otherwise
def isTouchingEdge(self):
    #6. write this function
    if self.ballDownY() >= 600:
        return True
    elif self.ballUpY() <= 0: 
        return True
    else:
        return False

    
#update: Called on draw. Draws the ball object on the screen and moves it 
#input: none
#output: none
def update(self):
    noFill() #change this color to change the color of your ball!
    self.y += self.dy
    self.x += self.dx
    translate(self.x, self.y, 0)
    sphere(self.r)

    touchingPaddleMTV = self.isTouchingPaddle()
    if touchingPaddleMTV != None:
        self.dx = -(self.dx)
        self.x -= touchingPaddleMTV[0]
        self.y -= touchingPaddleMTV[1]
    if self.isTouchingEdge():
        self.dy = -(self.dy)
    #7. be able to explain this logic to a coordinator
    # sign up on the TA list and do so!
    translate(self.x, self.y, 0)
    
    

#8 write getters for x, y, width, and height!
def getX(self):
        return self.x
    
def getY(self):
        return self.y
    
def getWidth(self):
        return self.w
    
def getRadius(self):
    return self.r

        

    
#randomNum: returns a random number between either (-1, -3) or (1, 3)
#input: none
#output: returns a random number between either (-1, -3) or (1, 3)
def randomNum(self):
    num = random(1, 3)
    isNegative = int(random(1) * 2)
    if isNegative == 0:
        num *= (-1)
    return num
    
#reset: moves the ball back to the given location and re-generates ball movement
#input: x, the x-coordinate to move the ball to
# y, the y-coordinate to move the ball to
#output: none
def reset(self, x, y):
    self.x = x
    self.y = y
    self.dx = self.randomNum()
    self.dy = self.randomNum()
            
#isTouchingPaddle: check if the ball is touching a paddle
#input: none
#output: the MTV to move if the ball is touching a paddle. Otherwise, None
def isTouchingPaddle(self):
    leftPaddleMTV = cd.collideBallPaddle(self, self.leftPaddle)
    rightPaddleMTB = cd.collideBallPaddle(self, self.rightPaddle)
    if leftPaddleMTV != None:
        return leftPaddleMTV
    else:
        return rightPaddleMTB

```

**collisionDetection.py**  
import math

#check if ball and paddle are colliding  
def collideBallPaddle(b, p):  
rPos = [p.getX(), p.getY()]  
rSize = [p.getWidth(), p.getHeight()]  
center = [b.getX(), b.getY()]

```
#'clamp' to rectangle coords
x = max(rPos[0], min(rPos[0] + rSize[0], center[0]))
y = max(rPos[1], min(rPos[1] + rSize[1], center[1]))
clampedPoint = [x, y]

if isInBoundsBall(b, clampedPoint): #if the center of the ball is in the paddle
    if isInBoundsPaddle(p, center):
        print "center of ball is in paddle"
        rightEdgeDist = rSize[0] + rPos[0] - center[0]
        leftEdgeDist = center[0] - rPos[0]
        topEdgeDist = center[1] - rPos[1]
        bottomEdgeDist = rSize[1] + rPos[1] - center[1]
        smallest = min(topEdgeDist, min(bottomEdgeDist, min(leftEdgeDist, rightEdgeDist)))
        
        rad = b.getWidth() / 2
        if smallest == topEdgeDist:
            return [0, topEdgeDist + rad]
        elif smallest == bottomEdgeDist:
            return [0, (-1) * bottomEdgeDist - rad]
        elif smallest == rightEdgeDist:
            return [(-1)*rightEdgeDist - rad, 0]
        elif smallest == leftEdgeDist:
            return [leftEdgeDist + rad, 0]                             
    else: # center not in paddle
        mtvLength = (b.getWidth() / 2) - getDistance(center, clampedPoint)
        connectingV = getDistanceVector(clampedPoint, center)
        scalar = sqrt((mtvLength*mtvLength)/(
                    (connectingV[0]*connectingV[0]) + (connectingV[1]*connectingV[1])))
        mtv = smult(connectingV, scalar)
        if mtv[0] == 0 and mtv[1] == 0:
            return None
        return mtv
return None

```

def isInBoundsBall(ball, p):  
c = [ball.getX(), ball.getY()]  
distance = (p[0] - c[0]) \* (p[0] - c[0]) + (p[1] - c[1]) \* (p[1] - c[1])  
radius = ball.getWidth() / 2  
return distance \<= radius \* radius

def isInBoundsPaddle(paddle, p):  
x = paddle.getX()  
y = paddle.getY()  
w = paddle.getWidth()  
h = paddle.getHeight()  
return (p[0] \>= x and p[0] \<= x + w and  
p[1] \>= y and p[1] \<= y + h)

def getDistanceVector(a, b):  
distanceX = a[0] - b[0]  
distanceY = a[1] - b[1]  
return [distanceX, distanceY]

def getDistance(a, b):  
distanceX = (a[0] - b[0])_(a[0] - b[0])  
distanceY = (a[1] - b[1])_(a[1] - b[1])  
return sqrt(distanceX + distanceY)

def smult(v, s):  
return [v[0]\*s, v[1]\*s]

**p1.py**  
import collisionDetection as cd  
global y

#a class for a Pong paddle that can move up and down  
class Paddle1:

```
# __init__ : creates a paddle
# input: x, the starting x-coordinate of the paddle
def __init__ (self, size, w, h, d, x, name):
    self.w = 20
    self.h = 100
    self.d = 60
    self.size = size
    self.x = 50 
    self.y = height / 2
    self.name = name

#moveUp: moves the paddle up by a given amount. Will stop the paddle
# from going off the edge of the screen
#input: amt, the amount to move up by
def moveUp(self, amt):
    #1. write this function!
    if self.y - amt >= 0:
        self.y -= amt
        print "the new y loc of " + self.name + " is " + str(self.y)
    
    
        
    
    

#moveDown: moves the paddle down by a given amount. Will stop the paddle
# from going off the edge of the screen
#input: amt, the amount to move down by
def moveDown(self, amt):
    #2. write this function!
    if self.y + amt + self.h <= 600:
        self.y += amt

    

#3. Write getters (see help slides) for y, x, width, and height

def getX(self):
    return self.x

def getY(self):
    return self.y

def getWidth(self):
    return self.w

def getHeight(self):
    return self.h

def getDepth(self):
    return self.d

# def getMouse(self):
# return mouseY    

        
        
#update: Called on draw. Draws the paddle object on the screen
#input: none
#output: none
def update(self):
    #change this color to change the color of your paddle!
    noFill()
    translate(self.x, self.y, 0)
    box(self.w, self.h, self.d)

```

**p2.py**  
import collisionDetection as cd  
#a class for a Pong paddle that can move up and down  
class p2:

```
# __init__ : creates a paddle
# input: x, the starting x-coordinate of the paddle
def __init__ (self, size, w, h, d, x, name):
    self.w = 20
    self.h = 100
    self.d = 60
    self.size = size
    self.x = 700 
    self.y = height / 2
    self.name = name
#moveUp: moves the paddle up by a given amount. Will stop the paddle
# from going off the edge of the screen
#input: amt, the amount to move up by
def moveUp(self, amt):
    #1. write this function!
    if self.y - amt >= 0:
        self.y -= amt
        print "the new y loc of " + self.name + " is " + str(self.y)
    
    
        
    
    

#moveDown: moves the paddle down by a given amount. Will stop the paddle
# from going off the edge of the screen
#input: amt, the amount to move down by
def moveDown(self, amt):
    #2. write this function!
    if self.y + amt + self.h <= 600:
        self.y += amt

    

#3. Write getters (see help slides) for y, x, width, and height

def getX(self):
    return self.x

def getY(self):
    return self.y

def getWidth(self):
    return self.w

def getHeight(self):
    return self.h

def getDepth(self):
    return self.d

# def getMouse(self):
# return mouseY    

        
        
#update: Called on draw. Draws the paddle object on the screen
#input: none
#output: none
def update(self):
    noFill() #change this color to change the color of your paddle!
    translate(self.x, self.y, 0)
    box(self.w, self.h, self.d)
```

---

<div class="post-metadata">

### Author: ![neilcsmith](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/neilcsmith/32/144_2.png) [@neilcsmith](https://discourse.processing.org/u/neilcsmith)
#### Post date: [July 26, 2018, 4:07pm UTC](https://discourse.processing.org/t/problem-with-mousemoved-function/2101/2 "2018-07-26T16:07:06Z")

</div>

At a guess you’re translating somewhere without translating back, resetting the matrix or pushing / popping the matrix.

---

<div class="post-metadata">

### Author: ![dan850](https://avatars.discourse-cdn.com/v4/letter/d/e9c0ed/32.png) [@dan850](https://discourse.processing.org/u/dan850)
#### Post date: [July 26, 2018, 11:18pm UTC](https://discourse.processing.org/t/problem-with-mousemoved-function/2101/3 "2018-07-26T23:18:21Z")

</div>

Hi @puddle Hope your getting closer to your solution. Also, so we can better assist you, make sure to keep your code within the tick marks:-) Feel free to send us an update. ![58%20PM](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/1X/37a038edd046d08846b191357e693681b737def8.png)
