2012-12-14 42 views
3

我有一個1000x600像素的畫布。我想在畫布之外產生精靈(但均勻分佈)。 檢索(-500,-500)和(1500,1100)之間但(0,0)和(1000,600)之間的隨機值的最佳方法是什麼?我知道一個while循環可以用來產生數字,直到他們在範圍內,但看起來多餘。謝謝。在x和y之間但不在a和b之間生成隨機數的最佳方法

回答

3

如果你想生成-500和1500之間的數字,不包括0到1000,你可以生成0和1000(0 - -500 + 1500 - 1000)之間的數字。

如果數字小於500,則減去500;如果數字是大於或等於500,加500

或者更一般:

function randomInt(outerMin, outerMax, innerMin, innerMax) 
{ 
    var usableRange = innerMin - outerMin + outerMax - innerMax, 
    threshold = innerMin - outerMin, 
    num = Math.floor(Math.random() * (usableRange + 1)); 

    if (num < threshold) { 
     return num - threshold; 
    } else { 
     return num - threshold + innerMax; 
    } 
} 

randomInt(-500, 1500, 0, 1000); 

二維點,你必須獲得更多的創造性。首先,你產生了禁區內兩點再傳到這些值的好的地區:

function randomVector(outer, inner) 
{ 
    var innerWidth = inner.right - inner.left, 
    innerHeight = inner.bottom - inner.top, 
    x = Math.floor(Math.random() * (innerWidth + 1)), 
    y = Math.floor(Math.random() * (innerHeight + 1)), 
    midx = Math.floor(innerWidth/2), 
    midy = Math.floor(innerHeight/2); 

    if (x < midx) { // left side of forbidden area, spread left 
     x = x/midx * (inner.left - outer.left) - inner.left; 
    } else { // right side of forbidden area, spread right 
     x = (x - midx)/midx * (outer.right - inner.right) + inner.right; 
    } 

    if (y < midy) { // top side of forbidden area, spread top 
     y = y/midy * (inner.top - outer.top) - inner.top; 
    } else { // bottom side of forbidden area, spread bottom 
     y = (y - midy)/midy * (outer.bottom - inner.bottom) + inner.bottom; 
    } 

    // at this point I'm not sure how to round them 
    // but it probably should have happened one step above :) 
    return { 
     x: Math.floor(x), 
     y: Math.floor(y) 
    } 
} 

randomVector({ 
    left: -500, 
    top: -500, 
    right: 1500, 
    bottom: 1100 
}, { 
    left: 0, 
    top: 0, 
    right: 1000, 
    bottom: 600 
}); 

重要

這工作,因爲你的「禁」區以外的區域都是平等在他們各自的維度,即padding-top == padding-bottom && padding-left == padding-right

如果這將不同,分佈不再統一。

+0

我認爲這不會解決這種情況下的問題,其中禁區是二維的。 – Philipp

+0

沒有,這將起作用,我只需要爲x做一次函數,然後爲y做一次。 (具有適當的值) – Sam

+0

@Philipp Sam正確,函數必須針對每個軸執行兩次:) –

0

只要產生和(0,0)之間的那些號碼(1,1),然後使用一些線性函數進行映射。

否則,除要在其中隨機座標落在矩形區域。假設你獲得N個這樣的矩形。通過將(0,0)和(1,1)之間的隨機生成器的輸出映射到該矩形(這是一個線性映射),可以填充每個矩形。

2

生成0和1000之間的隨機數,如果其超過500加500(或600 respectivly)如果不能否定它。

2

而是具有一組禁止矩形的,你可以計算一組允許的矩形。要在任何允許的矩形內獲得隨機位置,首先選擇一個隨機矩形,然後選擇該矩形內的隨機位置。

如果reticles的大小不一樣,則需要按面積加權,否則較小的矩形將比較大的矩形具有更高的密度(200x100矩形需要爲10x20矩形的100倍) 。

相關問題