Math.random();
// Tạo ra 1 số bất kỳ giữa 0 và 1 như 0.0105901374530933
Với số nguyên
Math.round(); // làm tròn số để thành số nguyên . ví dụ : 1,57→ 2
Math.ceil(); // thêm phần lẻ để thành số nguyên . ví dụ : 1,5 → 2
Math.floor(); // bỏ phần lẻ để thành số nguyên . ví dụ : 1,5 → 1
Tạo số bất kỳ giữa 2 số
Math.round(Math.random()); // kết quả kiểu như boolean là 0 hay là 1
Tạo số bất kỳ giữa nhiều số
Math.round(Math.random()*10); // kết quả xuất ra số nguyên ngẫu nhiên trong khoảng 0 - 10
Math.ceil(Math.random()*10); // kết quả xuất ra số nguyên ngẫu nhiên trong khoảng 1- 10
Math.round(Math.random()*15)+5; // kết quả xuất ra số nguyên ngẫu nhiên trong khoảng 5 - 20
Math.round(Math.random()*(y-x))+x; // kết quả xuất ra 1 số nguyên ngẫu nhiên giữa x và y
Ví dụ 1:
Tạo 1 button và 1 Dynamic text box có tên biến (variable) là "display". Click chọn button và nhập dòng code sau vào bảng lệnh action
on (release) {
display = Math.round (Math.random ()*200)-100;
}
And that's it! Now test your movie and give it a try out. You'll notice that the values in the code follow the pattern set by the general formula ie if x = -100, and y =100, then y-x=200 and +x = -100.
This can have many different applications within flash. For example, to have a movieclip appear in random positions on the screen between the values of 0 and 200 you could have the following. Note: movieclip instance is called "bob".
bob._x = Math.round(Math.random()*200); // movieClip "bob" có vị trí ngẫu nhiên từ 0 - 200 theo trục x
bob._y = Math.round(Math.random()*200); // movieClip "bob" có vị trí ngẫu nhiên từ 0 - 200 theo trục y
Or to set the size of a movieclip randomly (between 0 and 100):
bob._width = Math.round(Math.random()*100); // bề ngang movieClip "bob" có giá trị ngẩu nhiên từ 0 - 100
bob._height = Math.round(Math.random()*100); // chiều cao movieClip "bob" có giá trị ngẩu nhiên từ 0 - 100
Or to choose a random movieclip to load, say if our movieclips have a linkage name of "bob1", "bob2" and we have 5 of them:
i = Math.ceil(Math.random()*5);
attachmovie("bob"+i, "fred"+i, 1);
So that would attach a random movie, say "bob3", into level 1 and then give it an instance name of "fred3".
Well, that's the basics of using the random function in Flash 5. Hopefully now you will be able to incorporate this into your movies to produce some even more amazing flash work. =)
Random with movieClip:
- place:
- size:
- Alpha:
- Color:
- time:
- duplicate
reset.onRelease = dupMovie;
color = ["0x94B469", "0xD39E90", "0x8FB4A3"];
math = Math.floor(Math.random()*15+15);
trace(math);
MovieClip.prototype.setRGB = function(colorValue) {
new Color(this).setRGB(colorValue);
};
function dupMovie() {
for (i=0; i
http://www.actionscript.org/resources/articles/90/1/Maths-Functions-including-Random/Page1.html
Subpages (2): random color 1 random snow
0 nhận xét:
Đăng nhận xét