前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Unity】控制小球运动

【Unity】控制小球运动

作者头像
DevFrank
发布2024-07-24 14:53:03
610
发布2024-07-24 14:53:03
举报
文章被收录于专栏:C++开发学习交流

搭建场景

建立地面Plane、小球Player和四面墙Wall。

小球运动脚本

给小球创建一个刚体(有重力的物体),并添加一个Player脚本;

脚本编写如下:

代码语言:javascript
复制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public Rigidbody rd;    //public或者private(接口)

    // Start is called before the first frame update
    void Start()
    {
        //Debug.Log("游戏开始了!");
        rd = GetComponent<Rigidbody>(); // 调用刚体组件

    }

    // Update is called once per frame
    void Update()
    {
        //Debug.Log("游戏正在运行!");
        //rd.AddForce(Vector3.right); //施加1N(vector3.right left forward back)
        //rd.AddForce(new Vector3(10, 0, 0));  //自定义力

        float h = Input.GetAxis("Horizontal");  //keyboard A/D~~~-1/1
        float v = Input.GetAxis("Vertical");    //keyboard W/S~~~-1/1
        //Debug.Log(h); (1,2,3) * 2 = (2,4,6)   //加速
        rd.AddForce(new Vector3(h, 0, v));  //x y z
    }
}

相机跟随小球运动脚本

如果相机位置固定,小球运动的时候无法实时看到小球的运动,因此要让相机跟随运动,才有运动的效果;

给相机添加FollowTarget脚本,并关联小球刚体:

脚本编写如下:

代码语言:javascript
复制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FollowTarget : MonoBehaviour
{
    public Transform playerTransform;   //球的位置
    private Vector3 offset; //将offset定义在函数外(全局)

    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - playerTransform.position; //计算相机与小球距离
        //Vector3 offset;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = playerTransform.position + offset; //相机实时运动跟随
    }
}

效果展示

在这里插入图片描述
在这里插入图片描述

以上。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-07-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 搭建场景
  • 小球运动脚本
  • 相机跟随小球运动脚本
  • 效果展示
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档