Home > Tutorial

慣性運動及加速模擬系統

這系統是用來模擬加速及慣性運動的效果的,

如果未學過Trigonometric Functions的話,
就請先去學學,
因為本系統有用到基本的Trigonometric Functions。

先說一說思路,
加速時速度就會提升,

用角度把速度會分x 和 y

每次的圖片xy座標也會加上xy速度
而速度也會隨時間減慢,模擬摩擦力的效果。
轉向時,角度會增加或減少,
在轉向後,會有少許的餘轉,
也是模擬摩擦力的效果。
 
在測試或使用本系統前,
請先確定,\Graphics\Pictures\
內有Car.png的圖檔。
自己做一個25*25的白色正方形就行了。
 
 
#==============================================================================
# ■ Main
#------------------------------------------------------------------------------
#  各定義結束後、從這裡開始實際處理。
#==============================================================================
begin
  ACCELERATION = 0
  PI = 3.141592654
  Car = Sprite.new
  Car.bitmap = Bitmap.new("Graphics/Pictures/Car")
  Car.ox = Car.bitmap.width/2
  Car.oy = Car.bitmap.height/2
  Car.angle = 0
  Car.zoom_y = 1.5
  Car.x = 600.to_f
  Car.y = 240.to_f
  speed_x = 0
  speed_y = 0
  Turnspeed = 0
  #在這裡初始所需的變數
  loop do
    if Input.press?(Input::UP)
      ACCELERATION = 0.9
    else
      if Input.press?(Input::DOWN)
        ACCELERATION = -0.3
      end
    end
    #設定加速、減速的情況
    if Input.press?(Input::RIGHT)
      Turnspeed -= 0.5
      ACCELERATION /= 1.3
    end
    if Input.press?(Input::LEFT)
      Turnspeed += 0.5
      ACCELERATION /= 1.3
    end
    #設定轉左、轉右的情況
    if Input.press?(Input::A)
      break
    end
    angle = Car.angle / 180 * PI
    #把angle轉成radian
    speed_x -= Math.sin(angle) * ACCELERATION
    speed_y -= Math.cos(angle) * ACCELERATION
    #將acceleration分開成x和y 的speed
    #留意這裡,angle是用radian表示,
    #再用cosine和sine找出x和y,
    #如果不明白請參考有關數學書籍

    speed_x /= 1.05
    speed_y /= 1.05
    if speed_x < 0.07 and speed_x > -0.07
      speed_x = 0
    end
    if speed_y < 0.07 and speed_y  > -0.07
      speed_y = 0
    end
    #摩擦力的模擬減速
    ACCELERATION = 0
    #設定沒有加速的情況
    Car.angle %= 360
    #把角度限在360內,其實不做也行,
    #不過角度會太大,不好控制和使用
    speed_x = [speed_x , 10].min
    speed_y = [speed_y , 10].min
    #限制最大速度
    Car.x += speed_x
    Car.y += speed_y
    #xy座標的改變
    Car.x %= 640
    Car.y %=480
    #限制物體在畫面內
    Turnspeed = [[Turnspeed / 1.07 , 5].min , -5].max
    #餘轉的設定
    Car.angle += Turnspeed
    #角度改變
    Graphics.update
    Input.update 
  end
end
 
這裡只是基本的系統,
當然可以做換檔、煞車和車身重心轉移等等,
不過我不會在這裡說的了,
如果想知的話就問我或自己做吧!

回前頁

Hosted by www.Geocities.ws

1