Unity中我会的两种移动方式

Unity中我会的两种移动方式

  1. Transform.Translate移动,也是最基本的移动方式
 	public float speed = 5;//定义一个公有有的速度(后面的数值可以不填,随后在unity中调整,默认为1)
    void Update()
    {
        Move();//引用Move代码
    }
    void Move()
    {
    	if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.UpArrow))//如果按下W或上箭头
   		{
    		this.transform.Translate(Vector3.forward * speed * Time.deltaTime);
    	}
   		if (Input.GetKey(KeyCode.S) | Input.GetKey(KeyCode.DownArrow))//如果按下S或下箭头
		{
    		this.transform.Translate(Vector3.back * speed * Time.deltaTime);
		}
   		if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.LeftArrow))//如果按下A或左箭头
   		{
   			this.transform.Translate(Vector3.left * speed * Time.deltaTime);
   		}
   		if (Input.GetKey(KeyCode.D) | Input.GetKey(KeyCode.RightArrow))//如果按下D或右箭头
   		{
   			this.transform.Translate(Vector3.right * speed * Time.deltaTime);
   		}
	}
    
  1. Rigidbody(刚体)
    public Rigidbody rigid;
    public float speed;
    /*如果你选择在Unity里面赋值刚体那以下可以不用做
    void start()
    {
    	rigid = GetComponent<Rigidbody>();
	}
    */
    
    void FixedUpdate()
    {
        float horizontal = Input.GetAxis("Horizontal");//左右
        float vertical = Input.GetAxis("Vertical");//前后
        if (Input.GetKey(KeyCode.W)|Input.GetKey(KeyCode.S))
        {
           	rigid.velocity = Vector3.forward * vertical * speed;
        }
        if (Input.GetKey(KeyCode.A) | Input.GetKey(KeyCode.D))
        {
            rigid.velocity = Vector3.right * horizontal * speed;
        }
    }
  1. 总结
    以上的forward,back , left,right可以在unity的官方文档中查找到分别对应前后左右。
    其中update函数是每一帧执行一遍(start只是开始执行一遍),而fixedupdate则是每0.02秒执行一次,Time.deltaTime则是根据机型、电脑的配置自适应帧数,所以,如果是Update中就需要用Time.deltaTime来优化,但FixedUpdate中用Time.deltaTime的话就会显得速度很慢。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值