Autocad VBA初級教程 (第十一課:動畫基礎(chǔ))
說實(shí)話,用ACAD玩動畫絕對比不上專業(yè)的三維動畫軟件,不過這年頭自稱精通CAD的工程師太多了,而學(xué)會用ACAD玩動畫一定能提高您的競爭實(shí)力, 想象一下您用ACAD動畫向老板演示零件的裝配方法……
下面的例題是一個最簡單的動畫,由用戶選擇一個要移動的對象,然后定位起點(diǎn)和終點(diǎn),程序會慢慢地把對象移動。
移動方法:object.move 起點(diǎn)坐標(biāo),端點(diǎn)坐標(biāo)
Sub testmove()
Dim p0 As Variant '起點(diǎn)坐標(biāo)
Dim p1 As Variant '終點(diǎn)坐標(biāo)
Dim pc As Variant '移動時起點(diǎn)坐標(biāo)
Dim pe As Variant '移動時終點(diǎn)坐標(biāo)
Dim movx As Variant 'x軸增量
Dim movy As Variant 'y軸增量
Dim getobj As Object '移動對象
Dim movtimes As Integer '移動次數(shù)
ThisDrawing.Utility.GetEntity getobj, po, "請選擇移動對象"
p0 = ThisDrawing.Utility.GetPoint(, "起點(diǎn):")
p1 = ThisDrawing.Utility.GetPoint(p0, "終點(diǎn):")
pe = p0
pc = p0
motimes = 3000
movx = (p1(0) - p0(0)) / motimes
movy = (p1(1) - p0(1)) / motimes
For i = 1 To motimes
pe(0) = pc(0) + movx
pe(1) = pc(1) + movy
getobj.Move pc, pe '移動一段
getobj.Update '更新對象
Next
End Sub
先讓用戶選擇移動的對象、起點(diǎn)、終點(diǎn),motimes動畫是設(shè)置動畫幀數(shù),這個例程是讓對象移動3000小段,movx和movy是每一段移動的距離,然后進(jìn)行一個3000次的循環(huán),每一次循環(huán)移動一小段距離。
看第二個例題:做一個小輪子在一條山坡上運(yùn)動的動畫,山坡為正弦曲線。請注意,應(yīng)該用偏移法獲得輪圓心的軌跡才是正確的。編程思路:先畫好圓和橫軸,然后畫山坡,偏移獲得移動軌跡線,放到隱藏圖層中,然后根據(jù)軌跡線移動圓和軸,在移動之前先旋轉(zhuǎn)軸線。
旋轉(zhuǎn)方法:object. rotate 基點(diǎn),角度
偏移方法: object.offset(偏移量)
Sub moveball()
Dim ccball As Variant '圓
Dim ccline As Variant '圓軸
Dim cclinep1(0 To 2) As Double '圓軸端點(diǎn)1
Dim cclinep2(0 To 2) As Double '圓軸端點(diǎn)2
Dim cc(0 To 2) As Double '圓心
Dim hill As Variant '山坡線
Dim moveline As Variant '移動軌跡線
Dim lay1 As AcadLayer '放軌跡線的隱藏圖層
Dim vpoints As Variant '軌跡點(diǎn)
Dim movep(0 To 2) As Double '移動目標(biāo)點(diǎn)坐標(biāo)
cclinep1(0) = -0.1: cclinep2(0) = 0.1 '定義圓軸坐標(biāo)
Set ccline = ThisDrawing.ModelSpace.AddLine(cclinep1, cclinep2) '畫直線
Set ccball = ThisDrawing.ModelSpace.AddCircle(cc, 0.1) '畫半徑為0.1的圓
Dim p(0 To 719) As Double '申明正弦線頂點(diǎn)坐標(biāo)
For i = 0 To 718 Step 2 '開始畫多段線
p(i) = i * 3.1415926535897 / 360 '橫坐標(biāo)
p(i + 1) = Sin(p(i)) '縱坐標(biāo)
Next i
Set hill = ThisDrawing.ModelSpace.AddLightWeightPolyline(p) '畫正弦線即山坡曲線
hill.Update '顯示山坡線
moveline = hill.Offset(-0.1) '球心運(yùn)動軌跡線
vpoints = moveline(0).Coordinates '獲得規(guī)跡點(diǎn)
Set lay1 = ThisDrawing.Layers.Add("hidelay") '創(chuàng)建名為"hidelay"的圖層
lay1.LayerOn = False '關(guān)閉圖層
moveline(0).Layer = "hidelay" '將軌跡線放到關(guān)閉的圖層中
ZoomExtents '顯示整個圖形
For i = 0 To UBound(vpoints) - 1 Step 2
movep(0) = vpoints(i) '計算移動的軌跡
movep(1) = vpoints(i + 1)
ccline.Rotate cc, 0.05 '旋轉(zhuǎn)直線
ccline.Move cc, movep '移動直線
ccball.Move cc, movep '移動圓
cc(0) = movep(0) '把當(dāng)前位置作為下次移動的起點(diǎn)
cc(1) = movep(1)
For j = 1 To 50000 '這次循環(huán)的目的是讓小球移動得慢一點(diǎn),循環(huán)量應(yīng)根據(jù)自已的電腦速度設(shè)置
j = j * 1
Next j
ccline.Update '更新
Next i
End Sub
本課結(jié)束,請做思考題:在一條直線上畫兩個同樣大小的圓,然后讓這兩個圓沿直線相向而行,到互換位置后停下來,尺寸自定.
|