在C ++中使用Openframeworks库,我有一个发光半径(max_distance),它由拖过屏幕的鼠标拉伸(mouseDragX)决定。它工作正常。
但是不是每次我调整它(通过拖动鼠标),我希望它不要从0开始并直接跟随鼠标拖动。
max_distance = mouseDragX/2;
但是,如果我已经将鼠标拖到右边,在前一次拖动时说200,那么下次我拖动鼠标,然后进入相反方向(负数),max_distance的值减去该金额,而不仅仅是该金额。
我以为会是
max_distance += mouseDragX/2;
但这似乎完全杀了它
你能帮助我吗?
#include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
ofSetWindowShape(700,700);
max_distance = 700; // ofDist didn't work(?) // ofDist(0,0,700,700);
ofEnableSmoothing();
ofEnableAlphaBlending();
}
//--------------------------------------------------------------
void testApp::update(){
max_distance = mouseDragX/2;
if (max_distance < 0) max_distance = 0;
}
//--------------------------------------------------------------
void testApp::draw(){
string str = "mouseDragX: ";
str += ofToString(mouseDragX)+" ";
ofSetWindowTitle(str);
int i,j;
int height = ofGetHeight();
int width = ofGetWidth();
for(i = 0; i <= height; i += 20) {
for(j = 0; j <= width; j += 20) {
float dist_color = getDistance(mouseX, mouseY, i, j); // for definition of getDistance, look below!
dist_color = dist_color/max_distance * 100;
// to get the colors into the range between 0 and 255, multiply the values by 5.
ofSetColor(dist_color*5,dist_color*5,dist_color*5, 123);
ofEllipse(i, j, 20, 20);
}
}
}
//--------------------------------------------------------------
void testApp::keyPressed (int key){
}
//--------------------------------------------------------------
void testApp::keyReleased (int key){
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
// shift values down
for (int i = 0; i < 1; /*<<- length of array*/ i++) {
pmouseX[i] = pmouseX[i+1];
pmouseY[i] = pmouseY[i+1];
}
// make pmouseX/Y[0] be the previous mouse position. [1] = current
pmouseX[1] = mouseX;
pmouseY[1] = mouseY;
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
mouseDragX = (mouseX - pmouseX[0]);
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
// mouseDragX = mouseDragY = 0; // The drag starts here
}
//--------------------------------------------------------------
void testApp::mouseReleased(){
}
float testApp::getDistance(int startX, int startY, int endX, int endY){
return sqrt((endX-startX)*(endX-startX) + (endY-startY)*(endY-startY));
}
非常感谢你。
答案 0 :(得分:0)
如果max_distance
和mouseDragX
为int
值,则除以2将导致整数除法,从而导致损失。
如果mouseDragX
值在某个时间为1,则尤其如此。这将导致1 / 2
(整数除法)并返回0
。
示例:
让我们考虑mouseDragX
需要3个不同的值(3个周期):
3, 1, -4
可以预期max_distance
会增加(3 / 2) + (1 / 2) - (4 / 2) = 0
。
但由于整数截断,这将导致1 + 0 - 2 = -1
。
如果您使用float
而不是int
,并且当您真正需要它时,只需将max_distance
转换为int,该怎么办?
答案 1 :(得分:0)
如果我理解正确,你想做这样的事情。
// Every time the mouse *stops* moving, (say on mouse-up
// message) save previous max_distance
int base = max_distance;
// when mouse moves
max_distance = base + mouseDragX/2;