一、创建一个unity项目
二、Create所需3Dobject
1.Player创建一个cube命名为player
2.walls为了使player不出界增设walls
三、添加属性:
1.添加在Player上
添加脚本,把代码拖到Player
添加new script组件,并命名为PlayMove,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playMove : MonoBehaviour
{
public Rigidbody rd;
public float speadAutoMove=5;
public float speadMoveUpandDown=20;
// Start is called before the first frame update
void Start()
{
rd=gameObject.GetComponent
}
// Update is called once per frame
void Update()
{
PlayerAutoMove();
PlayerMoveUpandDown();
}
private void PlayerAutoMove(){
rd.AddForce(Vector3.right*speadAutoMove); //前进
}
private void PlayerMoveUpandDown()
{
float v=Input.GetAxis("Vertical"); //上下
rd.AddForce(v*Vector3.up*speadMoveUpandDown);//给一个上下的力量
}
}
2.添加到walls上,首先create empty将wall包含
在Wall上添加new script脚本,把代码拖到Walls,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class wallControl : MonoBehaviour
{
private float offset;
public GameObject player;
// Start is called before the first frame update
void Start()
{
offset=gameObject.transform.position.x-player.transform.position.x;
}
// Update is called once per frame
void Update()
{
FollowPlayMove();
}
void FollowPlayMove(){
gameObject.transform.position=new Vector3(player.transform.position.x+offset,0,0);
}
}
3.实现相机跟随
为了让方块运动时视角一样
在相机上添加new script 组件并命名为cameraControl,代码如下
String System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraControl : MonoBehaviour
{
public GameObject player;
private float offset_camera;
// Start is called before the first frame update
void Start()
{
offset_camera=gameObject.transform.position.x-player.transform.position.x;
}
// Update is called once per frame
void Update()
{
FollowCameraMove();
}
void FollowCameraMove(){
gameObject.transform.position=new Vector3(offset_camera+player.transform.position.x,gameObject.transform.position.y,gameObject.transform.position.z);
}
}
最后为Player设置位置的初始值,控制从什么位置开始移动。



