来源:
中国IT实验室
作者:
somesun
2008-03-18/11:21
想起前几天看到一个帖子,说的是如何实现"拖动小球在圆周上移动"的问题,今天有时间做了一个实例,代码不多,供像我这样的初级者参考。当看到“拖动小球在圆周上移动”这个问题时,我起初想的是单独做一个小球,再画个圆周,用数组记录圆周上各点的坐标,试验了,数据大多了,放弃。后来想,能不能从圆心角的变化入手,主意已定,动手制作,嘿嘿,还真不错。发上来供大家以后遇到相似问题时参考,老鸟们别笑话哦,因为是全AS2.0的,所以,以下代码直接拷贝到帖上就行了:
//===== 创建说明、输入文本 ==================
this.createTextField("titleTxt", 1, 50, 10, 40, 16);
this.createTextField("dynamicTxt", 2, 150, Stage.height-20, 40, 16);
this.createTextField("input_txt", 3, 232, Stage.height-20, 40, 16);
createTxt(titleTxt, di, "拖动小红球沿圆移动");
createTxt(dynamicTxt, di, "输入圆的半径创建图形:");
createTxt(input_txt, !di);
function createTxt(target:TextField, di:Boolean, txt:String) {
with (target) {
if (di) {
border = true;
borderColor = 0x000000;
textColor = 0xFF0000;
restrict = "0-9";
maxChars = 3;
type = "input";
} else {
autoSize = "center";
type = "dynamic";
text = txt;
selectable = false;
}
}
}
input_txt.onChanged = function() {
var num:Number = Number(this.text);
if (num<=Stage.height/2) {
createImag(num);
dynamicTxt.text = "输入圆的半径创建图形:";
} else {
dynamicTxt.text = "半径过大,重新输入";
}
};
//=== 与鼠标交互 ==================
createImag(120);
function createImag(r_num:Number) {
// 画圆circle | r 半径 | x0 y0 圆心坐标在舞台中央
var r:Number = r_num, x0:Number = Stage.width/2, y0:Number = Stage.height/2;
this.createEmptyMovieClip("circle", 4);
with (circle) {
lineStyle(1, 0x000000, 100);
moveTo(x0+r, y0);
}
for (var i:Number = 0; i<=360; i++) {
var p:Number = i*Math.PI/180;
circle.lineTo(x0+Math.cos(p)*r, y0+Math.sin(p)*r);
}
// 画小红球ball
this.createEmptyMovieClip("mc", 5);
mc.createEmptyMovieClip("ball", mc.getNextHighestDepth());
with (mc.ball) {
lineStyle(12, 0xFF0000, 100);
moveTo(r, 0);
lineTo(r+0.5, 0);
}
mc._x = x0;
mc._y = y0;
// drag === mouseObject 事件
var drag:Boolean = false;
var mouseObject:Object = new Object();
mouseObject.onMouseDown = function() {
if (mc.ball.hitTest(_root._xmouse, _root._ymouse)) {
drag = true;
}
};
mouseObject.onMouseMove = function() {
if (drag) {
// 赋值
var p1:Object = {x:_xmouse, y:_ymouse};
var p2:Object = {x:mc._x, y:mc._y};
mc._rotation = angle(p1, p2);
}
updateAfterEvent();
};
mouseObject.onMouseUp = function() {
drag = false;
};
Mouse.addListener(mouseObject);
//== 取得角度值
function angle(p1:Object, p2:Object) {
var xx:Number = p1.x-p2.x;
var yy:Number = p1.y-p2.y;
var r:Number = Math.atan2(yy, xx);
return radianToAngle(r);
}
//== 弧度轮换为角度
function radianToAngle(r:Number) {
return r*180/Math.PI;
}
}
看效果: