unity3d 打砖块操作及脚本

合集下载

Unity3D一些比较基本的脚本及组件(C#)

Unity3D一些比较基本的脚本及组件(C#)

Unity3D⼀些⽐较基本的脚本及组件(C#)通过代码创造图形//创建顶点,创建序列,创建⽹格,然后把⽹格赋给⽹格序列器//draw a trianglevoid Start () {Vector3[] vs = new Vector3[3];vs[0] = new Vector3(0,0,0);vs[1] = new Vector3(1,0,0);vs[2] = new Vector3(0,1,0);int[ts] = new int[3];ts[0] = 0;ts[1] = 1;ts[2] = 2; //要注意顺序,要⽤左⼿系,法线向外,拇指向外Mesh mesh = new Mesh();GetComponet<MeshFilter>().mesh = mesh;mesh.vertices = vs; // vertices⾄⾼点mesh.triangles = ts;}///* */////draw a triangle程序封装代码public GameObject Create Triangle(){GameObject obj = new GameObject(“Triangle”);MeshFilter mf = obj.AddComponet<MeshFilter>();obj.AddComponent<MeshRender>();Mesh mesh = new Mesh();mesh.vertices = nes[]{new Vector3(0,0,0);new Vector3(3,0,0);new Vector3(0,3,0);};mesh.triangles = new[]{0,2,1//不⽤分号,初始化系,直接把初始值放进去};mf.mesh = mesh;return obj;}Camera 的性质与使⽤public CameraClearFlags clearFlags; //clearFlags是相机清除表识public ColorbackgroundColor; //给定他的颜⾊,背景⾊,只有单⾊才起作⽤public int cullingMask; //提出掩码public class chapter6 : MonoBehaviour{public GameObject cube;void Start(){ber = 9; //把cube设置在第9层Camera cam = this.GetComponet<Camera>()’cam.clearFlags = CameraClearFlags.SolidColor;cam.backgroundColor = new Vector3(1,0,0,0); //表⽰设置颜⾊cam.cullingMask = 9; //表⽰第9层的都不会被渲染出来,也就是说cube不会显⽰出来}}//CameraClearFlags是⼀个枚举类型,有以下四个成员:solidColor 表⽰⽤backgroundColor所制定的填充背景skybox 表⽰天空盒,模拟天空效果填充Depth 只是清除深度缓存,保留上⼀帧所使⽤的颜⾊Nothing 不进⾏背景清除,这种情况在游戏和模拟应⽤中⽐较少⽤public bool orthographic;//⽤于读取和设定相机的投影⽅式,如果为true则表⽰是正交投影,否则为透视投影;正交投影可⽤于UI和2D开发public float orthographicSize; //⽤以指定正交投影的视景体的垂直⽅向尺⼨的⼀半public Rect rect; //相机对应的视⾓⼝的位置和⼤⼩,rect以单位化形式制定相机视⼝在屏幕中的位置和⼤⼩,位置⼤⼩取值范围为0~1,满屏为1Camera main = this.gameObject.GetComponet<Camera>();this.gameObject.SetActive(false);Camera cam0 = camGO0.AddComponet<Camera>();cam0.orthographic = true;cam0.transform.position = main.transform.position;cam0.transform.rotation = main.transform. rotation;cam0.orthographicSize = 2.0f; //指物体渲染后显⽰的⼤⼩远近,数值越⼤,相机视⼝越靠近该物体,从⽽该物体显⽰出来的更加⼤cam0.rect = new Rect(0f,0f, 0.5f, 0.5f); //前两个参数是camera的位置,后⾯两个参数设置相机⼤⼩(0.5f,0.5f)表⽰占x轴的⼆分之⼀,y轴的⼆分之⼀,所以总共占渲染窗⼝的四分之⼀Camera cam1 = camGO1.AddComponet<Camera>();cam1.orthographic = true;cam1.transform.position = main.transform.position;cam1.transform.rotation = main.transform. rotation;cam1.orthographicSize = 7.0f;cam1.rect = new Rect(0.5f, 0.5f, 0.5f, 0.5f);}Material,Shader,Texture(材质,着⾊器,纹理)光照、纹理等让物体更加的真实。

(2020年整理)Unity3D常用脚本.pptx

(2020年整理)Unity3D常用脚本.pptx
screenbutton = true; } } function OnGUI(){
if(screenbutton==true) if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-190,60,50),"Scene1")){
print("You click Scene1"); Application.LoadLevel (1); screenbutton = false; }else if(GUI.Button(Rect(Screen.width/2-380,Screen.height/2-130,60,50),"Scene2")){ print("You click Scene2"); Application.LoadLevel (2); screenbutton = false; }else if( GUI.Button(Rect(Screen.width/2-375,Screen.height/2-0,50,50),"Quit")){ print("You click Quit"); Application.Quit(); } } 心得: 场景转换时,这个程序贴在按钮界面场景中。在 Build Setting(导出)(在 File 下)菜单中加 入所需场景。
var particle : GameObject;
function Start(){ DontDestroyOnLoad(this); screnbutton=true;
word = Text; Text = ""; yield WaitForSeconds (2); TypeText ();

打砖块游戏编程实现

打砖块游戏编程实现

打砖块游戏编程实现打砖块游戏是一款经典的街机游戏,由于其简单而富有挑战性的玩法,一直备受玩家的喜爱。

在这篇文章中,将介绍打砖块游戏的编程实现,通过使用合适的格式来展示代码,以便清晰明了地呈现整个游戏开发的过程。

首先,我们需要创建一个游戏窗口,用于显示游戏界面。

借助常见的编程语言和相关引擎,如Python与Pygame,可以轻松地实现这一步骤。

以下是一个示例代码片段,展示了如何创建游戏窗口:```import pygame# 初始化游戏pygame.init()# 设置窗口大小window_width = 800window_height = 600window = pygame.display.set_mode((window_width, window_height)) pygame.display.set_caption("打砖块游戏")```接下来,我们需要在游戏窗口中绘制游戏元素,包括小球、挡板和砖块。

下面是一个示例代码片段,展示了如何在游戏窗口中绘制挡板:```# 绘制挡板paddle_width = 100paddle_height = 20paddle_x = window_width // 2 - paddle_width // 2paddle_y = window_height - paddle_height - 10paddle_color = (255, 255, 255)def draw_paddle():pygame.draw.rect(window, paddle_color, (paddle_x, paddle_y,paddle_width, paddle_height))```在游戏中,小球会从游戏窗口的顶部开始移动,并弹跳到窗口的边界和游戏元素之间。

我们需要编写代码来实现这种移动和弹跳的效果。

以下是一个示例代码片段,展示了如何移动和弹跳小球:```# 设置小球起始位置和速度ball_radius = 10ball_x = window_width // 2ball_y = window_height // 2ball_speed_x = 3ball_speed_y = 3ball_color = (255, 255, 255)def move_ball():global ball_x, ball_y, ball_speed_x, ball_speed_y# 在x轴上移动小球ball_x += ball_speed_x# 在y轴上移动小球ball_y += ball_speed_y# 检测小球与窗口边界碰撞if ball_x <= 0 or ball_x >= window_width - ball_radius:ball_speed_x *= -1if ball_y <= 0 or ball_y >= window_height - ball_radius:ball_speed_y *= -1# 检测小球与挡板碰撞if ball_x >= paddle_x and ball_x <= paddle_x + paddle_width and ball_y >= paddle_y - ball_radius:ball_speed_y *= -1# 检测小球与砖块碰撞# TODO: 编写检测小球与砖块碰撞的代码```最后,我们需要在游戏中加入交互性,让玩家能够通过操作挡板来控制小球的运动,并通过击碎砖块获得分数。

使用Unity开发3D游戏的基础教程

使用Unity开发3D游戏的基础教程

使用Unity开发3D游戏的基础教程第一章:Unity的介绍和安装Unity是一款强大的跨平台游戏开发引擎,可用于开发2D和3D游戏。

它拥有直观易用的界面和丰富的功能,适用于初学者和经验丰富的开发者。

在本章中,我们将介绍Unity的基础知识并帮助您安装和配置开发环境。

Unity支持多种平台,包括Windows、MacOS和Linux。

在开始之前,请确保您的计算机满足Unity的最低系统要求。

您可以从Unity官方网站下载并安装Unity Hub,它是一个用于管理Unity项目和版本的工具。

安装Unity之后,您可以通过Unity Hub打开编辑器。

Unity编辑器的界面分为多个窗口,如场景视图、资源视图、检查器视图和层次视图,从而使您能够轻松管理和操作游戏对象。

第二章:创建场景和游戏对象在Unity中,您可以创建场景来构建游戏世界。

场景是游戏中的虚拟空间,您可以在其中放置游戏对象和元素。

游戏对象是可以在场景中实例化的实体,如人物、道具、地形等。

要创建一个新场景,您可以在Unity编辑器中单击“File”菜单,然后选择“New Scene”。

接下来,您可以将游戏对象拖放到场景中,或使用Unity提供的创建工具来生成对象。

对于每个游戏对象,您可以在检查器视图中设置其属性和组件。

组件是游戏对象的功能模块,如碰撞器、脚本和动画控制器。

通过添加适当的组件,您可以控制游戏对象的行为和外观。

第三章:使用脚本编写游戏逻辑脚本是Unity中编写游戏逻辑的重要工具。

脚本是一种编程语言,可用于控制游戏对象的行为和交互。

在Unity中,您可以使用C#或Unity的自有语言UnityScript来编写脚本。

要创建一个新的脚本,您可以在Unity编辑器中单击“Assets”菜单,然后选择“Create”>“C# Script”。

然后,您可以使用Unity内置的脚本编辑器来编写和编辑脚本。

在脚本中,您可以定义类和方法来实现所需的游戏逻辑。

我学院:Unity3d动画脚本-Animation-Scripting使用方法

我学院:Unity3d动画脚本-Animation-Scripting使用方法

Unity3d动画脚本Animation Scripting使用方法Unity3d动画脚本 Animation Scripting(深入了解游戏引擎中的动画处理原理)也许这一篇文章的内容有点枯燥,但我要说的是如果你想深入的了解游戏引擎是如何处理动画片断或者素材并让玩家操控的角色动起来栩栩如生,那么这真是一篇好文章(当然我仅仅是翻译了一下)动画脚本 Animation ScriptingUnity's 动画系统允许你创建一个漂亮的动画蒙皮角色. 动画系统支持动画融合,混合,添加动画,步调周期时间同步.动画层.控制动画回放的所有方面(时间,速度,混合权重) 每个顶点有1.2.4个骨骼影响的mesh,基于物理系统的布娃娃系统,另外还有程序动画.为了获得最佳效果推荐您在制作模型和动画绑定前阅读一下 Modeling Optimized Characters 章节.制作一个动画角色主要包括两个方面; 在世界中移动和由此产生的动画. 如果你想了解角色移动相关的更多内容, 请参阅 Character Controller page. 实际上角色动画是由Unity's 脚本界面完成的 .你可以下载 example demos 中预设置好的动画角色. 当你学完本页的基础部分你还可以看一看 animation script interface.如果需要你可以点击并快速转到以下主题:· Animation Blending 动画融合· Animation Layers 动画层· Animation Mixing 动画混合· Additive Animation 附加动画· Procedural Animation 程序动画· Animation Playback 和 Sampling 动画重放和取样Animation Blending 动画融合在现今的游戏中Animation Blending是一项保证游戏动画顺畅过渡的基本的特性.动画师创建的动画例如: walk 循环, run 循环, idle原地空闲动画或射击动画.在游戏的任何时间点你都有可能从空闲站立转换到走动,反之亦然. 当然你不希望两个不同的动作之间突然跳转, 你需要动画平滑过渡.而这个问题的解决就依赖动画融合技术. 在Unity中你可以让同一个角色拥有任意数量的动画.所有这些动画融合添加成为一个总的动画.首先我们来为一个角色添加两个动画原地空闲站立和走动并平滑的使这两个动画过渡. 为了使我们在写脚本时简单些, 首先我们设置动画的 Wrap Mode为 Loop. 然后关闭 Play Automatically来让我们的脚本来独占动画的播放.我们第一个动画脚本很简单; 我们需要一些方法来探查角色移动的有多快, 然后在走和站立之间淡入淡出. 在这个简单的测试中我们使用 pre-setup input axes.function Update () {if (Input.GetAxis("Vertical") > 0.2)animation.CrossFade ("walk");elseanimation.CrossFade ("idle");}下面我们来让这个脚本运行:1. 创建一个js脚本 Assets->Create Other->Javascript.2. 把代码拷贝进去3. 把脚本拖拽给角色 character (It needs to be the same GameObject as the animation)点击Play 按钮, 当你按上下键时角色会走动,松开上下键时角色站立不动.动画层Animation Layers层是一个非常有用的概念它可以让你将动画片段任意成组并且区分优先顺序.在Unity's动画系统中, 你可以混合任意数量的动画片段. 你可以手工分配权重或者直接使用animation.CrossFade(),来自动分配权重.混合权重混合权重总是在应用前被规格化 normalized比如说我们现在有一个 walk cycle 和一个run cycle, 权重都是1 (100%).当unity计算最终动画时会规格化权重, 这意味着 walk占50% 权重, run cycle占50% 权重.这在大多数情况下都是不错的, 但当两个动画片段同时运行而其中一个权重明显大于另外一个. 那么你需要手动调整权重值,但如果你使用动画层来解决这个问题过程会容易得多.制作动画层的范例Layering Example例如现在你有一个射击动画, 一个空闲站立,一个走动循环. 你需要在走和站两个动作间持续的淡入淡出(在玩家走动速度的基础上) 但当玩家射击时我们只想展示射击动画. 因而射击动画此时的优先度最高.为了达到这一目的最简单的方法是在射击时简单的保持 walk 和 idle动画. 接下来需要确定shoot animation在一个比idle 和 walk更高的层. 这意味着shoot animation 将首先收到混合权重. walk 和idle 只有在 shoot animation不使用 100% 混合权重的情况下接收权重. 所以当 CrossFading the shoot animation in, 权重将从0开始很短时间内到达 100%. 在开始阶段 walk 和 idle 层将依然可以收到混合权重但当 shoot animation 完全切入时, 他们就收不到权重了. 这才是我们需要的!function Start () {// Set all animations to loop 设置所有动画为循环animation.wrapMode = WrapMode.Loop;// except shooting 除了射击(不循环)animation["shoot"].wrapMode = WrapMode.Once;//放置idle 和 walk 进低一级别的 layers (默认 layer 总是 0)// This will do two things这将作两件事情// - 当 calling CrossFade时,由于shoot 和 idle/walk 在不同的layers 中// 它们将不会影响互相之间的重放.// - 由于 shoot 在高一级的 layer, 当faded in 时shoot动画将替换// idle/walk 动画 .animation["shoot"].layer = 1;// Stop animations that are already playing停止已经播放的动画//(万一 user 忘记的话,自动disable播放)animation.Stop();}function Update () {// Based on the key that is pressed,基于按下的键// play the walk animation or the idle animation播放走,站动画if (Mathf.Abs(Input.GetAxis("Vertical")) > 0.1)animation.CrossFade("walk");elseanimation.CrossFade("idle");// Shoot射击if (Input.GetButtonDown ("Fire1"))animation.CrossFade("shoot");}默认情况下 animation.Play() 和 animation.CrossFade() 将停止或淡出在同一层里面的动画. 这是我们在绝大多数情况下需要的. 在我们shoot, idle, run 范例中, 播放 idle 和 run 将不会影响到 shoot动画反之亦然 (you can change this behavior(行为) with an optional parameter(任意参数) to animation.CrossFade if you like).动画混合Animation Mixing动画混合可以让你缩减你必须为游戏制作的动画片断数量,方法是制作只对身体某个部分起作用的动画. 这意味着这些动画可以和其他动画合并起来一起使用.如果你想给一个动画添加 animation mixing transform to an animation by calling AddMixingTransform() on the given AnimationState.混合范例Mixing Example例如你可能有一个挥手(hand-waving)动画. 你可能需要让一个空闲站立(idle)角色或者一个走动(walking)角色来挥手. 如果没有动画混合你可能需要制作两个挥手hand-waving 动画 : 一个给 idle, 一个给walking. 可是, 如果你将挥手(hand-waving)动画作为一个mixing transform 添加到shoulder transform,挥手动画将只控制肩膀. 身体余下部位不受其影响, 下半身会继续播放idle 或者walk 动画. 因而你只需要一个挥手(hand-waving)动画./// Adds a mixing transform using a Transform variablevar shoulder : Transform;animation["wave_hand"].AddMixingTransform(shoulder);Another example using a path.function Start () {// Adds a mixing transform using a path insteadvar mixTransform : Transform = transform.Find("root/upper_body/left_shoulder");animation["wave_h和"].AddMixingTransform(mixTransform);}附加动画 Additive Animations附加动画和动画混合可以让你缩减为游戏制作的动画片断的数量,并且对面部动画(facial animations)来说非常重要.让我们来看看如果创建一个在跑和转身时身体可以自动倾斜的角色.你已经制作好了一个 walk 和 run循环, 现在你还要制作一个走动左倾( walk-lean-left), 走动右倾(walk-lean-right), 跑左倾(run-lean-left), 跑右倾(run-lean-right)动画.这意味着你需要多做4个动画片断! 制作这么多数量的动画会累死人的. 而附加动画(Additive animations) 和混合(Mixing) 可以大大减少这些工作量!附加动画范例 Additive Animation Example附加动画允许你在顶层覆盖其他所有可能播放的动画的效果( allow you to overlay the effects of animation on top of any others that may be playing). 当你制作一个附加动画时, Unity将计算动画片断里的第一帧 (first frame)和当前帧(current frame)的差异. 然后它将在所有其他播放的动画之上应用这个差异(Then it will apply this difference on top of all other playing animations).现在你只需要制作一个左倾( lean-left) 和右倾( lean-right)动画. Unity将为此倾斜动画新建一个层并置于walk, idle 或 run循环的层级之上.下面是代码Here is the code to make that happen:private var leanLeft : AnimationState;private var leanRight : AnimationState;function Start () {leanLeft = animation["leanLeft"];leanRight = animation["leanRight"];// Put the leaning animation in a separate layer// So that other calls to CrossFade won't affect it. yer = 10;yer = 10;// Set the lean animation to be additive 混合模式为附加leanLeft.blendMode = AnimationBlendMode.Additive; leanRight.blendMode = AnimationBlendMode.Additive;// Set the lean animation ClampForever// With ClampForever animations will not stop// automatically when reaching the end of the clipleanLeft.wrapMode = WrapMode.ClampForever;leanRight.wrapMode = WrapMode.ClampForever;// Enable the animation 和 fade it in completely// We don't use animation.Play here because we manually adjust the time // in the Update function.// Instead we just enable the animation 和 set it to full weight leanRight.enabled = true;leanLeft.enabled = true;leanRight.weight = 1.0;leanLeft.weight = 1.0;// For testing just play "walk" animation 和 loop itanimation["walk"].wrapMode = WrapMode.Loop;animation.Play("walk");}// Every frame just set the normalized time// based on how much lean we want to applyfunction Update () {var lean = Input.GetAxis("Horizontal");// normalizedTime is 0 at the first frame 和 1 at the last frame in the clip leanLeft.normalizedTime = -lean;leanRight.normalizedTime = lean;}提示Tip:当使用附加动画时它会判断你同时也在播放一些其他的使用了附加动画的非附加动画(it is critical that you are also playing some other non-additive animation on every transform that is also used in the additive animation), 否则动画将添加到最后一帧结果的顶部(animations will add on top of the last frame's result). 这通常不是你所需要的 (This is most certainly not what you want).程序动画角色Procedurally Animating Characters有时你需要程序化的驱动你的角色骨骼. 例如你可能需要你的角色的头注视3d空间的某个点. 这个活最好让脚本来干. 幸运的是, Unity做这个很容易. 在Unity 中所有骨骼来驱动蒙皮网格(skinned mesh)的变换(Transforms). 因而你可以给角色的骨骼写脚本,就和其他GameObject一样.很重要的一点是动画系统updates the Transforms 是在Update() function调用之后,LateUpdate() function 调用之前. 因而如果你要调用 LookAt() function 你应该do that in LateUpdate() to make sure that you are really overriding the animation.布娃娃系统Ragdolls 也是用同样的方法制作出来的. 你可以简单的把刚性物体(Rigidbodies), 角色关节(Character Joints) 和胶囊碰撞体(Capsule Colliders)连接给不同的骨骼. 这样物理系统就可以作用于蒙皮角色(skinned character). (什么是布娃娃系统,当你在射击类游戏中打死对手时可以注意到当角色快接近地面时,他的四肢开始瘫软在地面上,这个不是动画师调出来的,而是布娃娃系统自动计算出来的。

Unity3D教程:脚本初级知识

Unity3D教程:脚本初级知识

Unity3D教程:脚本初级知识(一)脚本概览这是一个关于Unity内部脚本如何工作的简单概览。

Unity内部的脚本,是通过附加自定义脚本对象到游戏物体组成的。

在脚本对象内部不同志的函数被特定的事件调用。

最常用的列在下面:Update:这个函数在渲染一帧之前被调用,这里是大部分游戏行为代码被执行的地方,除了物理代码。

FixedUpdate:这个函数在每个物理时间步被调用一次,这是处理基于物理游戏的地方。

在任何函数之外的代码:在任何函数之外的代码在物体被加载的时候运行,这个可以用来初始化脚本状态。

注意:文档的这个部份假设你是用Javascript,参考用C#编写获取如何使用C#和Boo编写脚本的信息。

你也能定义事件句柄,它们的名称都以On开始,(例如OnCollisionEnter),为了查看完整的预定义事件的列表,参考MonoBehaviour 文档。

常用操作大多数游戏物体的操作是通过游戏物体的Transform或Rigidbody来做的,在行为脚本内部它们可以分别通过transform和rigidbody访问,因此如果你想绕着Y轴每帧旋转5度,你可以如下写:function Update(){transform.Rotate(0,5,0);}如果你想向前移动一个物体,你应该如下写:function Update(){transform.Translate(0,0,2);}跟踪时间Time类包含了一个非常重要的类变量,称为deltaTime,这个变量包含从上一次调用Update或FixedUpdate(根据你是在Update函数还是在FixedUpdate函数中)到现在的时间量。

所以对于上面的例子,修改它使这个物体以一个恒定的速度旋转而不依赖于帧率:function Update(){transform.Rotate(0,5*Time.deltaTime,0);}移动物体:function Update(){transform. Translate (0, ,0,2*Time.deltaTime);}如果你加或是减一个每帧改变的值,你应该将它与Time.deltaTime相乘。

Unity3D开发-C#脚本语言的一些基础用法

Unity3D开发-C#脚本语⾔的⼀些基础⽤法Unity 中C#语⾔的⼀些基础⽤法本⽂提供全流程,中⽂翻译。

Chinar坚持将简单的⽣活⽅式,带给世⼈!(拥有更好的阅读体验 —— ⾼分辨率⽤户请根据需求调整⽹页缩放⽐例)1Lerp —— 线性插值Mathf —— 数学运算函数库.Abs —— 函数,返回的是⼀个 float值,返回的是⼀个绝对值//插值运算//主相机背景⾊ = 颜⾊,插值(当前⾊,⽬标⾊,渐变速度)_mainCamera.backgroundColor = Color.Lerp(_mainCamera.backgroundColor, Color.green, _animationSpeed * Time.deltaTime);//主相机的正交尺⼨ = 运算,插值(当前尺⼨,⽬标尺⼨,渐变速度)_mainCamera.orthographicSize = Mathf.Lerp(_mainCamera.orthographicSize, 3.5f, _animationSpeed * Time.deltaTime);//判断是否达到⽬标值运算,计算向量(当前值减去 3.5f )< 0.01f的话跳出if (Mathf.Abs(_mainCamera.orthographicSize - 3.5f) < 0.01f) break;2LoadScene —— 载⼊场景scenemanagement —— 场景管理器SceneManager —— 场景管理LoadScene —— 加载场景.GetActiveScene() —— 获取激活的场景buildIndex —— 场景对应下标using UnityEngine;using UnityEngine.SceneManagement;//引⽤命名空间/// <summary>/// 测试脚本/// </summary>public class Test : MonoBehaviour{void Start(){SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); //重载当前场景}}3Gizmos —— ⼩物件注意:图⽚必须是在 Gizmos ⽂件夹下,需要在代码中“⽂件名.格式”写出格式OnDrawGizmos() —— 函数,是 MonoBehaviour 的⽣命周期函数,只在编辑状态下,每帧都会运⾏Gizmos.DrawIcon —— 在场景中某个位置绘制⼀张图⽚Gizmos.DrawCube —— 在场景中某个位置绘制⼀个CubeDebug.DrawLine —— 画⼀条线,这个⽅法也可在正常编译代码时打印⽤/// <summary>/// 编辑器模式⼯作,每帧都会运⾏/// </summary>void OnDrawGizmos(){Gizmos.DrawCube(transform.position, new Vector3(1, 1, 1)); //在Scene视窗下绘制⼀个Cube (位置,缩放⽐例)Gizmos.DrawIcon(transform.position, "Icon.png", true); //在Scene视窗下绘制⼀个图⽚(位置,名称.格式,是否允许扩展)Debug.DrawLine(transform.position, new Vector3(0, 10, 0), Color.green); //划线(开始位置,⽅向,颜⾊)}4Normalize —— 向量Vector3.Distance(transform.position,RightPos.position)>MaxDis三维向量.距离(当前位置,⽬标位置) > 最⼤距离if (Vector3.Distance(transform.position,RightPos.position)>MaxDis)//如果⼤于设定距离MaxDis{Vector3 pos = (transform.position - RightPos.position).normalized;//单位化向量,求得⽅向pos *= MaxDis;//给 pos 赋值,乘等于MaxDistransform.position = pos + RightPos.position;//当前位置赋值:最⼤距离+起点坐标点的位置}5RelativeVelocity —— 相对速度collision.relativeVelocity.magnitude > MaxSpeed碰撞物体的.相对速度.⼤⼩ > 最⼤速度/// <summary>/// 触发检测/// </summary>/// <param name="collision"></param>private void OnCollisionEnter2D(Collision2D collision){if (collision.relativeVelocity.magnitude > MaxSpeed) //如果相对速度.⼤⼩>最⼤速度{Destroy(gameObject); //直接死亡}else if (collision.relativeVelocity.magnitude > MinSpeed && collision.relativeVelocity.magnitude < MaxSpeed) //相对速度在4-8之间 {Render.sprite = HurtSprite; //更换图⽚,受伤}}6AudioSource —— ⾳频源AudioSource.PlayClipAtPoint(clip, transform.position);⾳频源.在指定位置播放裁剪⾳效(⾳效,位置)public AudioClip HurtClip; //受伤⾳效void Start(){AudioPlay(HurtClip);//播放受伤⾳效}/// <summary>/// 播放⾳效/// </summary>/// <param name="clip"></param>public void AudioPlay(AudioClip clip){AudioSource.PlayClipAtPoint(clip, transform.position); //静态⽅法:播放⾳效}7CameraFollow —— 相机跟随,插值Mathf.Clamp(posX, 0, 18)数学函数.范围(限定⽬标,0,到 18之间)/// <summary>/// 相机在指定范围跟随/// </summary>private void CameraFollow(){//记录Eva的横坐标float posX = transform.position.x;//相机当前位置 = 插值(当前相机位置,⽬标位置(Mathf.Clamp-限定范围:(限定posX,0,18之间))Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, new Vector3(Mathf.Clamp(posX, 0, 18), Camera.main.transform.position.y, Camera.main.transform.position.z), SmoothFlo * Time.deltaTime }8String Split —— 字符串分割例如⼀堆物体名字分别为:Test-1Test-2Test-3Test-4Test-5Split(‘-‘)函数:返回值为⼀个String数组⽤-拆分,输出的值为: 对应数组中:String[0]:对应TestString[1]:对应1,2,3,4,5SkinnedMeshRenderer[] parts = sourceTransform.GetComponentsInChildren<SkinnedMeshRenderer>(); //获取所有带有siki的物体位置信息,存⼊partsforeach (var part in parts)//遍历蒙⽪⽹格数组中的每⼀个元素{string[] nameStrings = .Split('-'); //记录名字,⽤-拆分,输出的值为: “Test-1”----对应数组中------0:"Test" 1:"1"if (!data.ContainsKey(nameStrings[0])) //如果字典GirlData中不包含第⼀个资源预设下的⼦物体的名字{GameObject partObj = new GameObject(); //实例化⼀个空物体 = nameStrings[0]; //给物体改名partObj.transform.parent = target.transform; //设置⽗物体mydic.Add(nameStrings[0], partObj.AddComponent<SkinnedMeshRenderer>()); //把⾻骼target⾝上的⾻骼信息存起来data.Add(nameStrings[0], new Dictionary<string, SkinnedMeshRenderer>()); //存到字典中}data[nameStrings[0]].Add(nameStrings[1], part); //存储所有的skin信息到字典}9Toggle/Button|AddListener —— Toggle/按钮添加监听需要引⽤命名空间:using UnityEngine.UI;private Toggle MyToggle;//⾃⾝的Toggle组件/// <summary>/// 初始化⽅法/// </summary>void Start(){if ( == "SaveButton") //如果按钮名为:SaveButton{Button but = GetComponent<Button>();but.onClick.AddListener(LoadScene); //给当前物体上的Button组件添加监听事件return; //不在向下执⾏}MyToggle = GetComponent<Toggle>();MyToggle.onValueChanged.AddListener(OnValueChangePerson); //绑定Toggle事件//MyToggle.onValueChanged.AddListener((bool value) => OnValueChangePerson(value)); //lambda表达式转换为委托类型}/// <summary>/// Toggle⽅法,改变/// </summary>/// <param name="isChange"></param>public void OnValueChangePerson(bool isChange){if (isChange){Debug.Log("开关状态 " + (isChange ? "On" : "Off"));}}/// <summary>/// 加载其他场景/// </summary>public void LoadScene(){SceneManager.LoadScene(1);}⽀持May Be —— 搞开发,总有⼀天要做的事!拥有⾃⼰的服务器,⽆需再找攻略!Chinar 提供⼀站式教程,闭眼式创建!为新⼿节省宝贵时间,避免采坑!1 ——2 ——3——4 ——ChinarEND本博客为⾮营利性个⼈原创,除部分有明确署名的作品外,所刊登的所有作品的著作权均为本⼈所拥有,本⼈保留所有法定权利。

unity3D快速教程

最近搭伙的大神基友失踪,所以在报案寻人之余决定利用这段时间独自起一个项目——Car t疯狂购物车(暂定称呼)。

现在已经完成前期工作,所以把流程写一下,方便那些刚刚使用U3D 并且喜欢单打独斗的新手对游戏开发流程有个大体的了解。

首先讲一下个人独立开发者的优劣势。

先说劣势吧:很明显,产能有限,不能做大项目。

需要熟悉各环节流程,容易出现技术瓶颈。

缺乏资金和时间支持,全职做生活要开销,业余时间做进度相当慢。

制作过程单一主观,缺乏调研和推广环节,大部分作品因此而失败。

优势:方便把握全局,不需要策划概念的交流过程和传达损耗。

各个环节的资源管理和适配效率高。

成本低流程短(相对的)。

最最关键的是自己的东西,全力以赴,容易出精品~~~关于产能和产品定位补充一下,做为个人开发者首先要按照实际情况来确定项目类型,首先大中型RPG游戏是不适合单人制作的,因为这种游戏的开发周期一般都超过甚至接近一年,而且项目庞大后期控制难度大。

主题类操控类的小游戏产品比较推荐。

个人开发者的项目周期建议不要超过半年,因为开发者往往会针对当前的市场情况和硬件性能来生产对应的游戏产品,而半年之后市场和硬件平台包括软件技术变化相对已经较大,小产品投放后可能难以产生最好效果。

手持平台的游戏主题选择建议越大众越好,如果是网络化的产品,那么建议越贴近女性越好,因为如果一个游戏女玩家越多,你就越不用担心男性玩家的数量,但是反过来则行不通,而且用户往往会是一些喜欢玩破解且不肯付钱的技术宅屌丝~~下面开始讲主要的首先是策划,这是作品成败决定性的一步,一个好的策划不但要玩过大量的游戏,而且能够准确的理解和剖析每个成功作品的成功因素。

大脑能够准确的模拟游戏规则所产生的用户行为和体验。

当你确定一个比较好的规则时,就可以进行原型制作,就是Demo的Demo,只为测试游戏主规则的可行性,Uniry在这方便有着非常大的优势。

原型甚至不需要模型和贴图,内置的资源拼接足够。

unity3d打砖块游戏代码

BrickBreaker GameStep 1: Create New Project “BrickBreaker”File -> New Project (check Standard Assets(Mobile).unityPackage)Then save the scene following below instruction. Change name of scene to “MainScene”. File -> Save SceneStep 2: Set Main CameraThe position, rotation and scale of Main Camera are showed following figure.Change background color whatever you want.Change projection perspective -> orthographicSize = 20Clipping Planes : Near = 0.3 Far = 25Step 3: Create Directional LightGameObject-> Create Other -> Directional LightStep 4: Create WallsCreate new cube following this instruction:GameObject -> Create Other -> CubeChange Cube Name to “ WallLeft”.“WallLeft” position, rotation and scale are following below figureChange “Main Color”.Create material from the “Project” section.Create -> MaterialName Material “wallMat” and change color. Then drag “wallMat” to the WallLeft.Create new cube following this instruction:GameObject -> Create Other -> CubeChange Cube Name to “ WallRight”.“WallRight” position, rotation and scale are following below figureChange ‘Main Color”Drag “wallMat” to the WallRight.Create new cube following this instruction:GameObject -> Create Other -> CubeChange Cube Name to “ WallTop”.“WallTop” position, rotation and scale are following below figureChange ‘Main Color”Then drag “wallMat” to the WallTop.Step 5: Create BricksGameObject -> Create Other -> CubeChange cube name to “brick”.“brick” position, rotation and scale are following below figure.Create new material from “Project” section and name “brickMat” and change color. Then drag to “brick”.Then copy “brick” 12 times following below figure.Step 6: Create BallWindows -> Asset StoreType ball pack and enter.Then click download button and import button to import to project this model.Then choose “eyeball” from the ball pack and drag to “scene”. “EyeBall” position, rotation and scale are following below figure.Add Rigidbody to “EyeBall” following below instruction.Component -> Physics -> RigidbodyMass = 0.01Uncheck “Use Gravity”Check Freeze Position -> ZAdd Sphere Collider to “EyeBall” following below figure. Component -> Physics -> Sphere Collider.Then select Material None -> BouncyStep 7: Create PaddleWindow - > Asset StoreType Hoverboard and click download button then click import button to import to project.Drag hoverboard to “Scene”. Name hoverboard to “Paddle”.Hoverboard position, rotation and scale are following below figure.Add Box Collider to Paddle following below instructionComponent -> Physics -> Box Collider Don’t change anything.Step 8: Create Score Text GameObject -> Create Other-> GUI Text Name GUI Text to Score.Change Text to “Score:”Step 9: Create PaddleControllerCreate new javascript from “Project“ section following below instructionCreate -> JavaScriptThen drag to “Paddle” on HierarchyPaddleController.jsfunction Update (){// paddle direction is just moved to x position right and left.transform.position.x = Camera.main.ScreenToWorldPoint (Input.mousePosition).x ; // x direction limit is from -19 to 11.transform.position.x = Mathf.Clamp( transform.position.x, -19, 11);}function OnCollisionEnter(collision : Collision){// collision overall speedvar velo = collision.rigidbody.velocity.magnitude;// collision speed is changing to x positioncollision.rigidbody.velocity.x = (collision.transform.position.x -transform.position.x)*8;if (collision.rigidbody.velocity.magnitude < velo){collision.rigidbody.velocity *= velo/collision.rigidbody.velocity.magnitude;}}Step 10: Create Ball directionCreate new javascript from project section following below instructionCreate -> JavaScriptThen drag to “Eyeball” on HierarchyBallDirection.js//initial value of speed multiply by 20.var initialSpeed : float = 20;function Start(){//xDir is x position range from -1.0 to 1.0 of Ball.var xDir : float = Random.Range(-1.0,1.0);//y = -1 when game starts ball randomly falling down.rigidbody.AddForce(Vector3( xDir, -1, 0) * initialSpeed );}Step 11: Create BrickDestroyCreate new javascript from project section following below instruction Create -> JavaScriptThen drag to “Eyeball” on HierarchyBrickDestroy.jsfunction OnCollisionEnter(myCol: Collision){if( == "brick"){// when ball collide with gameObject “brick”, score will be added by 1.Score.score++;// when ball collide with gameObject “brick” , brick will be destroyed.Destroy(myCol.gameObject);}}Step 12: Create GameOverCreate new scene following below instructionFile -> SceneThe Create new GUI Text following below instructionGameObject -> Create Other -> GUI TextChange Text to “Game Over”Change Anchor to “middle center”Change Font size to “71”Then build 2 scenes following below instruction.File -> Build Settings.Because after 1 scene the another scene has to work.Create new javascript from project section following below instruction Create -> JavaScriptThen drag to “Eyeball” on HierarchyGameOver.jsfunction Update () {//if y position of ball is lower than -20, “GameOver” scene will be appeared.if(rigidbody.position.y < -20){Application.LoadLevel("gameOver");}}Step 13: Create ScoreCreate new javascript from project section following below instruction Create -> JavaScriptThen drag to “Main Camera” on HierarchyScore.jsstatic var score : float = 0;var scoreText: GUIText;function Update(){//showing Score textscoreText.text = "Score : " + score;}Then Drag “Score” on Hierarchy to Score Text of “Main Camera”.Step 14: Create RestartCreate new javascript from project section following below instruction Create -> JavaScriptThen Open “GameOver” sceneThen drag to “Main Camera” on HierarchyRestart.js//if click mouse button on the scene, “MainScene” will be appeared.function Update() {if(Input.GetMouseButtonDown(0))Application.LoadLevel("MainScene");}。

unity3d中关于tilemap的几点用法

unity3d中关于tilemap的⼏点⽤法
上⾯的图⽚形象的展⽰出了unity中tilemap类的各⾃含义。

Tilemap API
getTile
setTile
Tilemap中的快捷键
{可以将tile⽡⽚进⾏旋转
shift + click擦除
Edit模式下可以对palette内的tile进⾏移动
Tilemap加碰撞体
1. 添加Tilemap Collider 2D组件
2. 如果想要将所有的碰撞体组合成⼀个,再添加Composite Collider 2D组件,但是这样会⾃动给物体添加刚体,把Body Type变为static物体就
不会因重⼒影响⽽下落。

并在Tilemap Collider 2D中选中Used by composite.
Ruletile
使⽤时就是对8个⽅向的内容进⾏勾选,如果该⽅向有内容就选勾,没有内容就打叉。

Rule中可以设置是否让该图⽚进⾏旋转
Collider中可以设置碰撞体模式,是⽹格化的还是沿着精灵图⽚画
Output中可以选择是⽤随机模式还是动图模式(可以调节动画的速率)
每个规则也是有先后调⽤顺序的。

笔刷
prefab Brush
可以刷预制体。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
//FixedUpdate会在每个固定的时间间隔被调用,
void FixedUpdate()
{ //得到用户输入,用输入轴实现平滑输入
float h = Input .GetAxis( "Horizontal");
//得到游戏对象上的刚体组件
//vector2:代表2D向量和点
//.Right相当于0,0点到1,0点的向量
FixedUpdate则不受帧率的变化,它是以固定的时间间隔来被调用,那么这个时间间隔怎么设置呢?Edit->Project Setting->time下面的Fixed timestep。
public class bat : MonoBehaviour {
public float speed = 150f;
}
要访问绑定了该script的object的其他属性,打钩组件的属性必须要getcomponent后才能访问
另一种访问属性的方法是先定义gameobject类型或其他类的类型,然后拖入
访问时必须先写组件名(transform)再.属性
如果发现text字没有显示可能是文本框划的不够大
ball中
public float x = 0.2f;
实现全局变量Enter类中:
public static int blocknum = 20;
其他类中:
Enter.blocknum -= 1;
HP类中:
public static int hp =1;
void Update () {
GetComponent< Text >() .text= ("HP:" +hp);
public class ball : MonoBehaviour {
public float speed = 100f;
public ball Ball;
public bat Bat;
public Text title;
// Use this for initialization
void Start () {
拖到colider的material
这样小球就具有弹性了,而且无摩擦
设置rigid的mass质量为0.0001
collision detection =continuous
interpolate =interpolate
gravity初始设为0
在ball界面可以更改speed
把ball旋转关了,避免小球速度突然降为0
原因:未将使用过的函数destory导致其仍然生效
实现将ball与bat连接:
HingeJoint2D铰链
将发射时的坐标设置为跟着bat的坐标:
void Start () {
Vector3 ballvtr = transform.position;//将ball的向量赋给ballvtr
ballvtr.x = Bat.transform.position.x-1.3f; //小数不能漏f
}
}
float hitVector( Vector2 ballpos,Vector2 batpos, float batwidth)
{ //返回球撞击处占bat宽度的比例,注意要是float
return (ballpos.x - batpos.x) / batwidth;
}
public float x = 0.2f;
public float y = -90.2f;
void Update()
{
if (transform.position.y<-110)
{
HP .hp -= 1;
Instantiate(Ball, new Vector2 (x, y), Quaternion.identity);
Destroy(gameObject); //不要忘记把原来的对象删掉,不然会fatal
}
}
实现球随拍子移动
若出现问题:The object of type 'ball' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
}
//框架方法当发生碰撞时调用
void OnCollisionEnter2D( Collision2D col) {//col指撞击的对象
if ( == "bat" )
{
float x = hitVector(transform.position, col.transform.position,
Vector3 ballvtr = transform.position;//将ball的向量赋给ballvtr
ballvtr.x = Bat.transform.position.x-1.3f; //小数不能漏f
transform.position = ballvtr;
Ball.GetComponent< HingeJoint2D >().enabled = true ;
}
if (Input .GetKeyUp( KeyCode.Space)) //按键要放在UPDATE才会生效
{
Ball.GetComponent< HingeJoint2D >().enabled = false ;
//使铰链失效,但不能删掉
GetComponent< Rigidbody2D >().velocity = Vector2 .up * speed;
transform.position = ballvtr;
GetComponent< Rigidbody2D >().velocity = Vector2 .up * speed;
}
附上代码
BALL类
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
camera clear flag改为solid color固定的颜色
设置background
size =125使游戏视图高度为125*2
图片format设为truecolor
图片属性可以ze rotation冻结z轴旋转,从而不让bat旋转出平面,不在z轴旋转
public float y = -90.2f;
void Update()
{
if (transform.position.y<-110)
{
HP .hp -= 1;
Instantiate(Ball, new Vector2 (x, y), Quaternion.identity);
Destroy(gameObject); //不要忘记把原来的对象删掉,不然会fatal
freeze position y使bat不能在y轴移动
gravity scale=0
FixedUpdate会在每个固定的时间间隔被调用,
那么要是Update和FixedUpdate的时间间隔一样,是不是就一样呢?答案是不一定,因为Update受当前渲染的物体,更确切的说是三角形的数量影响,有时快有时慢,帧率会变化,update被调用的时间间隔就发生变化。但是
col.collider.bounds.size.x); //从撞向的对象的碰撞体的size获得其宽度
Vector2 dir = new Vector2(x, 1).normalized; //单位化向量方向
GetComponent< Rigidbody2D >().velocity = dir * speed;//改变方向
GetComponent< Rigidbody2D >().velocity=Vector2 .right*h*speed;
}
}
给bat和边框加上box colider 2d
注意colider的size是按图片大小来的,最好要贴着框架
还有bat的colider要贴着轮廓
用offset可以调整还有edit
object sortinglayer add
选择+增加层unity会从上往下绘制层
将ball和bat放在下面的层
记住要把背景上的object都放在下面的层,才能避免绘制问题
设置好ball的组件
create physics material 2d
fraction摩擦系数设为0
bounciness弹性系数设为1
}
}
}
相关文档
最新文档