2017-11-12 22:20:08 YongshuangZhao 阅读数 1168

在游戏中,经常会用到相机震动功能,例如赛车游戏。现在我们来实现一个简单的相机震动功能。

代码如下:挂载在任意游戏对象上即可。

using UnityEngine;
using System.Collections;

public class CameraShake : MonoBehaviour
{
//抖动的物体
public Transform shakeTransform;
//抖动的频率
public float shakeTime = 0.002f;

//抖动的计时器
private float shakeTimer;
//记录抖动前的位置
private Vector3 currentPosition;
//设置抖动次数
private int shakeCount = -1;
void Start ()
{
//若为空,则默认相机抖动
if(shakeTransform == null)
shakeTransform = Camera.main.transform;
//记录抖动前的位置
currentPosition = shakeTransform.position;
//设置抖动次数
shakeCount = Random.Range (50, 60);
}
void Update ()
{
shakeTimer += Time.deltaTime;
if(shakeTimer>shakeTime && shakeCount > 0)
{
shakeCount --;
float shakeDelta = Random.Range (-0.01f, 0.01f);
//抖动最后一次时设置为都动前记录的位置
if(shakeCount == 1)
shakeDelta = 0;
shakeTimer = 0;
shakeTransform.position = currentPosition + Vector3.one * shakeDelta;
}
}
}

2017-12-10 18:19:59 YongshuangZhao 阅读数 336

此篇把之前的相机功能进行了汇总,通过一个枚举类型进行切换。功能如下:

followInching:跟踪加缓动效果
freeInching:自由加缓动效果
onlyFollow:仅跟踪视角
onlyFree:仅自由视角
none:正常相机

代码如下:

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[System.Serializable]
public class CameraData {
	public Transform target;//相机所看目标点,若target==null,则相机为自由视角,否则为跟踪视角
	public float yMinLimit = -50.0f;//y最小角度视角限制
	public float yMaxLimit = 90.0f;//y最大角度视角限制
	public float xMinRangeLimit = float.MinValue;//x最小限制距离
	public float xMaxRangeLimit = float.MaxValue;//x最大限制距离
	public float yMinRangeLimit = float.MinValue;//y最小限制距离
	public float yMaxRangeLimit = float.MaxValue;//y最大限制距离
	public float zMinRangeLimit = float.MinValue;//z最小距离限制
	public float zMaxRangeLimit = float.MaxValue;//z最大距离限制
	public float minDistanceToTarget = 0.0f;//距离目标最小距离
	public float maxDistanceToTarget = 10.0f;//距离目标最大距离
	public float xSpeed = 200.0f;//x角度旋转速度
	public float ySpeed = 120.0f;//y角度旋转速度
	public float scaleSpeed = 4.0f;//缩放速度
	public float xMoveSpeed = 4.0f;//x方向平移速度
	public float yMoveSpeed = 4.0f;//y方向平移速度
	public float lerpSpeed = 5.0f;//差值速度(缓动速度)

	//实时变化
	[HideInInspector]
	public float distance = 5.0f;//相机与目标点距离
	[HideInInspector]
	public float xCurrentAngle = 50.0f;//当前x角度
	[HideInInspector]
	public float yCurrentAngle = 25.0f;//当前y角度
	[HideInInspector]
	public float x, y;
}
public class CameraControl : MonoBehaviour {
	public enum Angle {
		followInching,//跟踪加缓动效果
		freeInching,//自由加缓动效果
		onlyFollow,//仅跟踪视角
		onlyFree,//仅自由视角
		none//正常相机
	}

	public CameraData cameraData;//Camera数据
	public Angle angle;//初始默认视角

	private float slowlySpeed = 2.0f;//缓动速度
	private float zCurrentScale = 0.0f;//当前缩放
	private float xCurrentScale = 0.0f;//当前横向平移
	private float yCurrentScale = 0.0f;//当前纵向平移

	private Vector2 oldPosition1;
	private Vector2 oldPosition2;

	void Update() {
		if (Input.GetKeyDown(KeyCode.F5)) {
			cameraData.x = 0;
			cameraData.y = 0;
		}
		switch (angle) {
		case Angle.followInching:
			if (cameraData.target != null) {
				FollowAngle (true);
			} else {
				FreeAngle (true);
			}
			break;
		case Angle.freeInching:
			FreeAngle (true);
			break;
		case Angle.onlyFollow:
			if (cameraData.target != null) {
				FollowAngle (false);
			} else {
				FreeAngle (false);
			}
			break;
		case Angle.onlyFree:
			FreeAngle (false);
			break;
		case Angle.none:
			break;
		default:
			break;
		}
	}
	/// <summary>
	/// 自由视角
	/// </summary>
	/// <param name="isSlowAction">是否缓动判断</param>
	void FreeAngle(bool isSlowAction) {
		#region 旋转
		if (Input.GetMouseButton(1)) {
			cameraData.xCurrentAngle += Input.GetAxis("Mouse X") * cameraData.xSpeed * Time.deltaTime;
			cameraData.yCurrentAngle -= Input.GetAxis("Mouse Y") * cameraData.ySpeed * Time.deltaTime;
			cameraData.yCurrentAngle = ClampAngle(cameraData.yCurrentAngle, cameraData.yMinLimit, cameraData.yMaxLimit);//y旋转角度限制
		}
		Quaternion rotationTo = Quaternion.Euler(cameraData.yCurrentAngle, cameraData.xCurrentAngle, 0);
		#endregion
		#region 缩放
		if (Input.GetAxis("Mouse ScrollWheel") != 0.0f) {
			zCurrentScale = Input.GetAxis("Mouse ScrollWheel") * cameraData.scaleSpeed;
		}
		#endregion
		#region 平移
		if (Input.GetMouseButton(0)) {
			xCurrentScale = -Input.GetAxis("Mouse X") * Time.deltaTime * cameraData.xMoveSpeed;
			yCurrentScale = -Input.GetAxis("Mouse Y") * Time.deltaTime * cameraData.yMoveSpeed;
			xCurrentScale = xCurrentScale > 1 ? 1 : xCurrentScale;
			yCurrentScale = yCurrentScale > 1 ? 1 : yCurrentScale;
			xCurrentScale = xCurrentScale < -1 ? -1 : xCurrentScale;
			yCurrentScale = yCurrentScale < -1 ? -1 : yCurrentScale;
		}
		#endregion
		if (isSlowAction)//带缓动效果
        {
			transform.rotation = Quaternion.Lerp(transform.rotation, rotationTo, Time.deltaTime * cameraData.lerpSpeed);
			transform.position = Vector3.Lerp(transform.position, transform.position + transform.forward * (zCurrentScale > 0 ? ((zCurrentScale -= Time.deltaTime * slowlySpeed) < 0 ? zCurrentScale = 0 : zCurrentScale) : ((zCurrentScale += Time.deltaTime * slowlySpeed) > 0 ? zCurrentScale = 0 : zCurrentScale)) + transform.right * (xCurrentScale > 0 ? ((xCurrentScale -= Time.deltaTime * slowlySpeed) < 0 ? xCurrentScale = 0 : xCurrentScale) : ((xCurrentScale += Time.deltaTime * slowlySpeed) > 0 ? xCurrentScale = 0 : xCurrentScale)) + transform.up * (yCurrentScale > 0 ? ((yCurrentScale -= Time.deltaTime * slowlySpeed) < 0 ? yCurrentScale = 0 : yCurrentScale) : ((yCurrentScale += Time.deltaTime * slowlySpeed) > 0 ? yCurrentScale = 0 : yCurrentScale)), Time.deltaTime * cameraData.lerpSpeed);
		}
		else//正常
        {
			Vector3 positionTo = rotationTo * new Vector3(xCurrentScale, yCurrentScale, zCurrentScale) + transform.position;
			xCurrentScale = 0;
			yCurrentScale = 0;
			zCurrentScale = 0;
			transform.rotation = rotationTo;
			transform.position = positionTo;
		}
		transform.position = new Vector3(Mathf.Clamp(transform.position.x, cameraData.xMinRangeLimit, cameraData.xMaxRangeLimit), Mathf.Clamp(transform.position.y, cameraData.yMinRangeLimit, cameraData.yMaxRangeLimit), Mathf.Clamp(transform.position.z, cameraData.zMinRangeLimit, cameraData.zMaxRangeLimit));//自由模式区域限制
	}
	/// <summary>
	/// 跟踪视角
	/// </summary>
	/// <param name="isSlowAction">是否缓动判断</param>
	void FollowAngle (bool isSlowAction)
	{
		if (Input.GetMouseButton (1)) {
			cameraData.xCurrentAngle += Input.GetAxis ("Mouse X") * cameraData.xSpeed * Time.deltaTime;
			cameraData.yCurrentAngle -= Input.GetAxis ("Mouse Y") * cameraData.ySpeed * Time.deltaTime;
			cameraData.yCurrentAngle = ClampAngle (cameraData.yCurrentAngle, cameraData.yMinLimit, cameraData.yMaxLimit);//y旋转角度限制
		}
		if (Input.GetMouseButton (0)) {
			xCurrentScale = -Input.GetAxis ("Mouse X") * Time.deltaTime * cameraData.xMoveSpeed;
			yCurrentScale = -Input.GetAxis ("Mouse Y") * Time.deltaTime * cameraData.yMoveSpeed;
			cameraData.x += xCurrentScale;
			cameraData.x = Mathf.Clamp (cameraData.x, cameraData.xMinRangeLimit, cameraData.xMaxRangeLimit);
			cameraData.y += yCurrentScale;
			cameraData.y = Mathf.Clamp (cameraData.y, cameraData.yMinRangeLimit, cameraData.yMaxRangeLimit);
		}
		cameraData.distance -= Input.GetAxis ("Mouse ScrollWheel") * cameraData.scaleSpeed;
		cameraData.distance = Mathf.Clamp (cameraData.distance, cameraData.minDistanceToTarget, cameraData.maxDistanceToTarget);//缩放距离限制
		Quaternion rotationTo = Quaternion.Euler (cameraData.yCurrentAngle, cameraData.xCurrentAngle, 0);
		Vector3 positionTo = rotationTo * new Vector3 (cameraData.x, cameraData.y, -cameraData.distance) + cameraData.target.position;
		if (isSlowAction) {//带缓动效果
			transform.rotation = Quaternion.Lerp (transform.rotation, rotationTo, Time.deltaTime * cameraData.lerpSpeed);
			transform.position = Vector3.Lerp (transform.position, positionTo, Time.deltaTime * cameraData.lerpSpeed);
		} else {//正常
			transform.rotation = rotationTo;
			transform.position = positionTo;
		}
	}
	/// <summary>
	/// 限制视角旋转角度
	/// </summary>
	/// <param name="angle">当前角度</param>
	/// <param name="min">最小旋转角度</param>
	/// <param name="max">最大旋转角度</param>
	/// <returns></returns>
	float ClampAngle(float angle, float min, float max) {
		if (angle < -360)
			angle += 360;
		if (angle > 360)
			angle -= 360;
		return Mathf.Clamp(angle, min, max);
	}
	//检测是否放大还是缩小
	public bool isEnlarge(Vector2 oP1, Vector2 oP2, Vector2 nP1, Vector2 nP2)
	{
		float leng1 = Mathf.Sqrt((oP1.x - oP2.x) * (oP1.x - oP2.x) + (oP1.y - oP2.y) * (oP1.y - oP2.y));
		float leng2 = Mathf.Sqrt((nP1.x - nP2.x) * (nP1.x - nP2.x) + (nP1.y - nP2.y) * (nP1.y - nP2.y));
		if (leng1 < leng2)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

2015-04-03 10:23:01 a3636987 阅读数 2199

经过一段时间的学习,学得以下第三视觉相机控制方法,当设置相机初始高度较高的状态下,相机有由高到低的效果,适合做为外景相机,如果是做室内相机,需要另外设计。将这个分享给大家,同时希望得到阅读者宝贵的意见,废话不多说,贴代码:

/// <summary>
/// Created by Hong Youwei
/// Created in 2015.3.25
/// </summary>

using UnityEngine;
using System.Collections;

public class CameraControl : MonoBehaviour {
	// 高度移动变化速度和旋转变化速度
	public float HeDamping = 2f;
	public float RoDamping = 3f;
	//相对主角的位置
	public float distance = 5f;
	public float height = 5f;
	
	//游戏对象和对象位置
	public GameObject target;
	Transform target_tf;
	
	// 游戏结束,相机围绕角色旋转的速度
	public float rotateSpeed = 20;
	
	void Start()
	{
		// 获取角色对象
		if (!target) {
			target = GameObject.FindGameObjectWithTag ("Player");
		}
	}
	
	void LateUpdate() {
		// 获取角色对象当前位置
		target_tf = target.transform;
		
		float wantRotationAngle = target_tf.eulerAngles.y;//想要旋转的角度 Y
		float wantHeight = target_tf.position.y + height; //想要的高度
		
		float currentRotationAngle = transform.eulerAngles.y;//当前旋转角度Y
		float currentHeight = transform.position.y;//当前高度
		
		currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantRotationAngle, Time.deltaTime * RoDamping);//当前旋转角度差值
		currentHeight = Mathf.Lerp (currentHeight, wantHeight, Time.deltaTime * HeDamping);//当前高度差值
		
		Quaternion currentRotation = Quaternion.Euler (new Vector3 (0, currentRotationAngle, 0));//当前旋转只Y
		transform.position = target_tf.position;
		transform.position -= currentRotation * Vector3.forward * distance;//与主角的相对位置
		transform.position = new Vector3 (transform.position.x, currentHeight, transform.position.z);//设置位置,关键高度

		Quaternion mR;
		mR = Quaternion.LookRotation (target_tf.position - transform.position);//创建一个旋转
		transform.rotation = Quaternion.Slerp (transform.rotation, mR, Time.deltaTime * RoDamping);//控制跟随人物旋转
		transform.LookAt (target_tf);
	}
	
}



2017-05-05 12:51:26 u010838555 阅读数 4787

此篇博文解决的问题是:

     1、unity3d如何访问android SD卡的文件

     2、如果把android端代码以jar包形式由unity3d调用

闲话不多说,现在咱们进入正题。

一、unity3d如何访问android SD卡的文件

        实现效果是unity3d调用android相册或相机,选择一张图片剪裁后,将图片肯绘制到unity3d中。

        解决这个问题,首先需要明白的是unity3d的资源存放目录,因为unity3d支持跨平台特性,所以资源文件的存放必然遵循一定的规则,否则很可能在不同的平台上编译会出现问题。

Unity3D中的资源路径

Application.dataPath 此属性用于返回程序的数据文件所在文件夹的路径。例如在Editor中就是Assets了。
Application.streamingAssetsPath 此属性用于返回流数据的缓存目录,返回路径为相对路径,适合设置一些外部数据文件的路径。
Application.persistentDataPath 此属性用于返回一个持久化数据存储目录的路径,可以在此路径下存储一些持久化的数据文件。
Application.temporaryCachePath 此属性用于返回一个临时数据的缓存目录。












android平台对应的资源路径

Application.dataPath /data/app/xxx.xxx.xxx.apk
Application.streamingAssetsPath jar:file:///data/app/xxx.xxx.xxx.apk/!/assets
Application.persistentDataPath /data/data/xxx.xxx.xxx/files
Application.temporaryCachePath /data/data/xxx.xxx.xxx/cache






具体的Unity3d的资源及目录说明可参考:http://www.tuicool.com/articles/qMNnmm6 ,此处不再缀述。

因此如果我们想要访问andorid SD卡上的文件,必须使用持久化数据存储目录 Application.persistentDataPath,它在android上对应的目录为Android/data/xxx.xx.xx/files/ 文件夹。也就是说,unity3d读取android SD中的文件目录是固定的,这是一个私有目录。下面我们来实现这一功能。效果是,从相册中选择一张照片,剪裁后,讲照片保存到android app安装目录下的files文件夹中,然后由unity3d读取此图片,绘制到屏幕上。

1、我们创建一个Android工程,取名为UnitySDK,此工程的目的是把我们的android端代码打包成一个jar包,放入Unity3d中使用,这里使用的是Eclipse,记住包名需跟unity3D android配置里的包名保持一致。


2、把我们的项目设置为一个Library

   

3、从unity的安装目录中找出classes.jar包,不同电脑文件存放位置可能不同,Windows平台如果使用mono方式的话,此文件在\Editor\Data\PlaybackEngines\AndroidPlayer\Variations\mono\Release\Classes 中。将jar包引用到我们的项目中。

4、将MainActivity继承自UnityPlayerActivity 并移除setContentView()方法,这是因为UnityPlayerActivity 继承自Activity,它里面已经设置了unityPlayer作为界面渲染,如果不移除setContentView()方法,则会造成复写,看不到unity3d的界面。MainActivity里的代码如下:

public class MainActivity extends UnityPlayerActivity {
	Context mContext = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
	}
	// Unity中会调用这个方法,用于区分打开摄像机 开始本地相册
	public void TakePhoto(String str) {
		Intent intent = new Intent(mContext, WebViewActivity.class);
		intent.putExtra("type", str);
		this.startActivity(intent);
	}
}

   在此我们定义了一个TakePhoto方法,,同时将处理结果交给WebViewActivity处理。WebViewActivity的代码如下,它的作用是用于打开相册/相机,选择照片后,进行剪裁,最后将剪裁结果保存到Android/data/com.demo.unity/files/ 目录下供unity3d调用。

public class WebViewActivity extends Activity {

	ImageView imageView = null;

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果

	public static final String IMAGE_UNSPECIFIED = "image/*";

	public final static String FILE_NAME = "image.png";
	public final static String DATA_URL = "/data/data/";

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_webview);

		imageView = (ImageView) this.findViewById(R.id.imageID);

		String type = this.getIntent().getStringExtra("type");

		// 在这里判断是打开本地相册还是直接照相
		if (type.equals("takePhoto")) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
			startActivityForResult(intent, PHOTOHRAPH);
		} else {
			Intent intent = new Intent(Intent.ACTION_PICK, null);
			intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
			startActivityForResult(intent, PHOTOZOOM);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == NONE)
			return;
		// 拍照
		if (requestCode == PHOTOHRAPH) {
			// 设置文件保存路径这里放在跟目录下
			File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == PHOTOZOOM) {
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == PHOTORESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {

				Bitmap photo = extras.getParcelable("data");
				imageView.setImageBitmap(photo);

				try {
					SaveBitmap(photo);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}

	public void SaveBitmap(Bitmap bitmap) throws IOException {

		FileOutputStream fOut = null;
		// 注解1
//		String path = "/mnt/sdcard/Android/data/com.xys/files";
		String path = "/storage/emulated/0/Android/data/com.demo.unity/files";
		try {
			// 查看这个路径是否存在,
			// 如果并没有这个路径,
			// 创建这个路径
			File destDir = new File(path);
			if (!destDir.exists()) {
				destDir.mkdirs();
			}

			fOut = new FileOutputStream(path + "/" + FILE_NAME);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		// 将Bitmap对象写入本地路径中,Unity在去相同的路径来读取这个文件
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
              // 通知Unity开始在"/mnt/sdcard/Android/data/com.xys/files";路径中读取图片资源,并且现在在Unity中
	   	UnityPlayer.UnitySendMessage("Main Camera", "message", FILE_NAME);
		finish();
}}


注意 com.demo.unity是我项目的包名,实际使用过程中请注意替换。

WebViewActivity布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
        android:layout_gravity="center"
        android:id="@+id/imageID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


Manifest中代码如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo.unity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="14" />
    <!-- 连接互联网的权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- SDCard中创建与删除文件权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <!-- SDCard写入数据权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.demo.unity.MainActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.demo.unity.TestActivity0"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
        </activity>
        <activity
            android:name="com.demo.unity.WebViewActivity"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
        </activity>
    </application>
</manifest>


      注意: 把android:theme换成android自带的主题


5、至此,android端代码基本编写完成,clean一下项目,在bin目录下找到 对应jar包,此jar包即为unity3d需要用到的jar包。

6、创建unity项目,并在Assets目录下依次创建 Plugins 和Android文件夹,将android 资源文件放到res目录下,Eclipse里的jar包,放到bin目录下,Manifest文件,放到 Android文件夹下:

      注意:values中的style文件、dimen文件不要复制过去



7、编写Main Camera 的 C#文件,MainControl,代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MainControl : MonoBehaviour {
	public GUISkin skin;
	Texture texture;
	string path="";
	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
		//当用户按下手机的返回键或home键退出游戏
		if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(KeyCode.Home) )
		{
			Application.Quit();
		}
	}
	void OnGUI()
	{
		GUILayout.Button (path, GUILayout.Height (100));

		GUI.skin = skin;
		if(GUILayout.Button("打开手机相册",GUILayout.Height(100)))
		{
			//调用我们制作的Android插件打开手机相册
			AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
			jo.Call("TakePhoto","takeSave");

		}
		if(GUILayout.Button("打开手机摄像机",GUILayout.Height(100)))
		{
			//调用我们制作的Android插件打开手机摄像机
			AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
			jo.Call("TakePhoto","takePhoto");

		}
			

		if(texture != null)
		{
			//注意! 我们在这里绘制Texture对象,该对象是通过
			//我们制作的Android插件得到的,当这个对象不等于空的时候
			//直接绘制。
			GUI.DrawTexture(new Rect(300,300,600,600),texture);
		}
			

	}
	void message(string str){
		StartCoroutine(LoadTexture(str));
	}
	IEnumerator LoadTexture(string name)
	{
		//注解1
		 path  =  "file://" + Application.persistentDataPath +"/" + name;

		WWW www = new WWW(path);
		while (!www.isDone)
		{

		}
		yield return www;
		//为贴图赋值
		texture = www.texture;
	}
}


最后来张效果图~:




     源码地址:https://pan.baidu.com/s/1bo7ezDl    其中,UnityDemo为unity创建的项目,UnitySDK为android项目。


没有更多推荐了,返回首页