在 Android 游戏中添加震动效果
2010-03-25 16:56:00 来源:WEB开发网正在开发第二个游戏,计时就要结束的时候,为了营造紧张的气氛,会利用手机自身的震动模拟心跳效果,其实这个心跳效果做起来真的非常的简单。所以直接上代码了(注意模拟器是模拟不了震动的,得真机测试哦):程序效果:
Java代码
package com.ray.test;
import android.app.Activity;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MotionEvent;
public class TestViberation extends Activity {
Vibrator vibrator;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStop() {
if(null!=vibrator){
vibrator.cancel();
}
super.onStop();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
long[] pattern = {800, 50, 400, 30}; // OFF/ON/OFF/ON...
vibrator.vibrate(pattern, 2);//-1 不重复,非-1为从pattern的指定下标开始重复
}
return super.onTouchEvent(event);
}
}
赞助商链接