axis2的405 Error: Method Not Allowed问题

zh919919 2013-07-11 03:43:01
第一次玩AXIS2,试过2种方式,一种是普通调用,一种是RPC调用,结果都一样。看了下代码也没发现访问方法有什么错误。错误代码如下:
org.apache.axis2.AxisFault: Transport error: 405 Error: Method Not Allowed
at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:310)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSendr.java:194)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:531)

...全文
809 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
zh919919 2013-08-06
  • 打赏
  • 举报
回复
引用 10 楼 fangmingshijie 的回复:
加上auth.setPreemptiveAuthentication(true);看下
加上这个还是不行,不过现在已经用CXF实现了。感谢帮助
  • 打赏
  • 举报
回复
加上auth.setPreemptiveAuthentication(true);看下
  • 打赏
  • 举报
回复
引用 7 楼 zh919919 的回复:
[quote=引用 6 楼 fangmingshijie 的回复:] 应该是你的参数中有中文乱码引起的,看看是否有中文参数。
参数里面没有任何中文,全是数字和字母。为了确保不是参数问题我将所有参数置为空依然出现这个错误。 不过刚刚意外的发现我写的权限验证并没有起作用,难道是这个引起的?

HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();         
auth.setUsername(USER_NAME);         
auth.setPassword(USER_PWD);           
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth); 
[/quote] 应该有影响。
zh919919 2013-07-16
  • 打赏
  • 举报
回复
引用 6 楼 fangmingshijie 的回复:
应该是你的参数中有中文乱码引起的,看看是否有中文参数。
参数里面没有任何中文,全是数字和字母。为了确保不是参数问题我将所有参数置为空依然出现这个错误。 不过刚刚意外的发现我写的权限验证并没有起作用,难道是这个引起的?

HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();         
auth.setUsername(USER_NAME);         
auth.setPassword(USER_PWD);           
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth); 
zh919919 2013-07-16
  • 打赏
  • 举报
回复
引用 8 楼 fangmingshijie 的回复:
[quote=引用 7 楼 zh919919 的回复:] [quote=引用 6 楼 fangmingshijie 的回复:] 应该是你的参数中有中文乱码引起的,看看是否有中文参数。
参数里面没有任何中文,全是数字和字母。为了确保不是参数问题我将所有参数置为空依然出现这个错误。 不过刚刚意外的发现我写的权限验证并没有起作用,难道是这个引起的?

HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();         
auth.setUsername(USER_NAME);         
auth.setPassword(USER_PWD);           
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth); 
[/quote] 应该有影响。[/quote] 这种写法是参照官网的API写的,刚刚试了直接写到header里传过去也无效。现在准备用CXF试试。
  • 打赏
  • 举报
回复
应该是你的参数中有中文乱码引起的,看看是否有中文参数。
zh919919 2013-07-15
  • 打赏
  • 举报
回复
没人会么?看来要换个技术调用了
oh_Maxy 2013-07-11
  • 打赏
  • 举报
回复
我玩的是axis1.4 wsdd形式发布服务。 里面有一个allowedmethod节点,会列出所有允许的服务。不晓得Axis2有没有类似的东东
zh919919 2013-07-11
  • 打赏
  • 举报
回复
这都要下班了也没个大神出现么?
zh919919 2013-07-11
  • 打赏
  • 举报
回复
以上是代码,求大神出现。
zh919919 2013-07-11
  • 打赏
  • 举报
回复

private static final String url = "接口地址";
	
private static final String QNAME_URL = "命名空间";
	
private static final String USER_NAME = "账号";
	
private static final String USER_PWD = "密码";

public static void ServiceClient(){
		try {
			ServiceClient client = new ServiceClient();
			
			client.setOptions(buildOptions());

			OMElement element = client.sendReceive(buildParam());
			
			Iterator it = element.getChildElements();
			
			while(it.hasNext()){
				OMElement omElement = (OMElement) it.next();
				System.out.println(omElement.getText());
			}

		} catch (AxisFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}

public static Options buildOptions(){
		Options options = new Options();
		
		options.setTo(new EndpointReference(url));
		
		options.setAction("GetJITOrderList");
		
		HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
		auth.setUsername(USER_NAME);
		auth.setPassword(USER_PWD);

		options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
		
		options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
		
		return options;
	}

public static OMElement buildParam(){
		OMFactory factory = OMAbstractFactory.getOMFactory();
		
		OMNamespace namespace = factory.createOMNamespace(QNAME_URL, "tns");
		
		OMElement date = factory.createOMElement("MT_JITInfo_Request",namespace);
		
		OMElement input = factory.createOMElement("DATUM",namespace);
		input.addChild(factory.createOMText(input, "20130609"));
		
		OMElement input2 = factory.createOMElement("ORDER",namespace);
		input2.addChild(factory.createOMText(input2, "X"));
		
		OMElement input3 = factory.createOMElement("MATNR",namespace);
		input3.addChild(factory.createOMText(input3, "X"));
		
		OMElement input4 = factory.createOMElement("ZTBBJ",namespace);
		input4.addChild(factory.createOMText(input4, "X"));
		
		date.addChild(input);
		date.addChild(input2);
		date.addChild(input3);
		date.addChild(input4);
		
		return date;
	}
Table of Contents Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parameter Ordering Names and Order of Includes Scoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Static and Global Variables Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x Naming General Naming Rules File Names Type Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules Comments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments Formatting Line Length Non-ASCII Characters Spaces vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization Preprocessor Directives Class Format Constructor Initializer Lists Namespace Formatting Horizontal Whitespace Vertical Whitespace Exceptions to the Rules Existing Non-conformant Code Windows Code Important Note Displaying Hidden Details in this Guide link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. Background C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency. Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Files In general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function. Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. The #define Guard link ▶All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Header File Dependencies link ▶Don't use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files. You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h". How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare static data members of type Foo. This is because static data members are defined outside the class definition. On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo. Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files. Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files. Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, instead of myfile.cc. Inline Functions link ▶Define functions inline only when they are small, say, 10 lines or less. Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions. Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. Decision: A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed). It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators. The -inl.h Files link ▶You may use file names with a -inl.h suffix to define complex inline functions when needed. The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage. If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary. Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read. Do not forget that a -inl.h file requires a #define guard just like any other header file. Function Parameter Ordering link ▶When defining a function, parameter order is: inputs, then outputs. Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Names and Order of Includes link ▶Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h. All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as #include "base/logging.h" In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows: dir2/foo2.h (preferred location — see details below). C system files. C++ system files. Other libraries' .h files. Your project's .h files. The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #included in some .cc. dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basictypes_test.cc and base/basictypes.h), but can be in different directories too. Within each section it is nice to order the includes alphabetically. For example, the includes in google-awesome-project/src/foo/internal/fooserver.cc might look like this: #include "foo/public/fooserver.h" // Preferred location. #include #include #include #include #include "base/basictypes.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" Scoping Namespaces link ▶Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive. Definition: Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros: Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide. Cons: Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR). Decision: Use namespaces according to the policy described below. Unnamed Namespaces Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts: namespace { // This is in a .cc file. // The content of a namespace is not indented enum { kUnused, kEOF, kError }; // Commonly used tokens. bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF. } // namespace However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment // namespace. Do not use unnamed namespaces in .h files. Named Namespaces Named namespaces should be used as follows: Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from other namespaces: // In the .h file namespace mynamespace { // All declarations are within the namespace scope. // Notice the lack of indentation. class MyClass { public: ... void Foo(); }; } // namespace mynamespace // In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. void MyClass::Foo() { ... } } // namespace mynamespace The typical .cc file might have more complex detail, including the need to reference classes in other namespaces. #include "a.h" DEFINE_bool(someflag, false, "dummy flag"); class C; // Forward declaration of class C in the global namespace. namespace a { class A; } // Forward declaration of a::A. namespace b { ...code for b... // Code goes against the left margin. } // namespace b Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file. You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files. // OK in .cc files. // Must be in a function, method or class in .h files. using ::foo::bar; Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods. // Shorten access to some commonly used names in .cc files. namespace fbz = ::foo::bar::baz; // Shorten access to some commonly used names (in a .h file). namespace librarian { // The following alias is available to all files including // this header (in namespace librarian): // alias names should therefore be chosen consistently // within a project. namespace pd_s = ::pipeline_diagnostics::sidetable; inline void my_inline_function() { // namespace alias local to a function (or method). namespace fbz = ::foo::bar::baz; ... } } // namespace librarian Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible. Nested Classes link ▶Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope. Definition: A class can define another class within it; this is also called a member class. class Foo { private: // Bar is a member class, nested within Foo. class Bar { ... }; }; Pros: This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation. Cons: Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo. Decision: Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method. Nonmember, Static Member, and Global Functions link ▶Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Cons: Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Decision: Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library. If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope. Local Variables link ▶Place a function's variables in the narrowest scope possible, and initialize variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g. int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g. while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global Variables link ▶Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction. Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD. The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals. Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the destructor for a static 'string' variable might be run prior to the destructor for another variable that contains a reference to that string. As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or string (use const char []). If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid. Classes Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in Constructors link ▶In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. Definition: It is possible to perform initialization in the body of the constructor. Pros: Convenience in typing. No need to worry about whether the class has been initialized or not. Cons: The problems with doing work in constructors are: There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden). If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state. If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion. If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code. For instance, gflags will not yet have been initialized. Decision: If your object requires non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc. Default Constructors link ▶You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly. Definition: The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays). Pros: Initializing structures by default, to hold "impossible" values, makes debugging much easier. Cons: Extra work for you, the code writer. Decision: If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid. The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly. If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor. Explicit Constructors link ▶Use the C++ keyword explicit for constructors with one argument. Definition: Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion. Pros: Avoids undesirable conversions. Cons: None. Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name); The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments. Copy Constructors link ▶Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN. Definition: The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value. Pros: Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation. Cons: Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected. Decision: Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container. If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator. If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error). For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used: // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) Then, in class Foo: class Foo { public: Foo(int f); ~Foo(); private: DISALLOW_COPY_AND_ASSIGN(Foo); }; Structs vs. Classes link ▶Use a struct only for passive objects that carry data; everything else is a class. The struct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(), Reset(), Validate(). If more functionality is required, a class is more appropriate. If in doubt, make it a class. For consistency with STL, you can use struct instead of class for functors and traits. Note that member variables in structs and classes have different naming rules. Inheritance link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public. Definition: When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interface inheritance, in which only method names are inherited. Pros: Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. Cons: For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class. Decision: All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo. Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual. Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private. When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not. Multiple Inheritance link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix. Definition: Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure interfaces and those that have an implementation. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance). Cons: Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix. Note: There is an exception to this rule on Windows. Interfaces link ▶Classes that satisfy certain conditions are allowed, but not required, to end with an Interface suffix. Definition: A class is a pure interface if it meets the following requirements: It has only public pure virtual ("= 0") methods and static methods (but see below for destructor). It may not have non-static data members. It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the Interface suffix. An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. Pros: Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers. Cons: The Interface suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients. Decision: A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface. Operator Overloading link ▶Do not overload operators except in rare, special circumstances. Definition: A class can define that operators such as + and / operate on the class as if it were a built-in type. Pros: Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. Cons: While operator overloading can make code more intuitive, it has several drawbacks: It can fool our intuition into thinking that expensive operations are cheap, built-in operations. It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==. Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug. Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared. Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared. However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why. See also Copy Constructors and Function Overloading. Access Control link ▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private. The definitions of accessors are usually inlined in the header file. See also Inheritance and Function Names. Declaration Order link ▶Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc. Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them. Within each section, the declarations generally should be in the following order: Typedefs and Enums Constants (static const data members) Constructors Destructor Methods, including static methods Data Members (except static const data members) Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class. See Copy Constructors. Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible. Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. Write Short Functions link ▶Prefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Google-Specific Magic There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Smart Pointers link ▶If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr. "Smart" pointers are objects that act like pointers but have added semantics. When a scoped_ptr is destroyed, for instance, it deletes the object it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last pointer to an object deletes it. Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this design is that it is easy to create circular references or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned. Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem. cpplint link ▶Use cpplint.py to detect style errors. cpplint.py is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting // NOLINT at the end of the line. Some projects have instructions on how to run cpplint.py from their project tools. If the project you are contributing to does not, you can download cpplint.py separately. Other C++ Features Reference Arguments link ▶All parameters passed by reference must be labeled const. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val). Pros: Defining a parameter as reference avoids ugly code like (*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that NULL is not a possible value. Cons: References can be confusing, as they have value syntax but pointer semantics. Decision: Within function parameter lists all references must be const: void Foo(const string &in, string *out); In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters. One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too. Function Overloading link ▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that takes a const string& and overload it with another that takes const char*. class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. Decision: If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append(). Default Arguments link ▶We do not allow default function parameters, except in a few uncommon situations explained below. Pros: Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Cons: People often figure out how to use an API by looking at existing code that uses it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code. Decision: Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of. One specific exception is when default arguments are used to simulate variable-length argument lists. // Support up to 4 params by using a default empty AlphaNum. string StrCat(const AlphaNum &a, const AlphaNum &b = gEmptyAlphaNum, const AlphaNum &c = gEmptyAlphaNum, const AlphaNum &d = gEmptyAlphaNum); Variable-Length Arrays and alloca() link ▶We do not allow variable-length arrays or alloca(). Pros: Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient. Cons: Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but dies mysteriously in production". Decision: Use a safe allocator instead, such as scoped_ptr/scoped_array. Friends link ▶We allow use of friend classes and functions, within reason. Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests. Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. Exceptions link ▶We do not use C++ exceptions. Pros: Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes. Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries. Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively. Exceptions are really handy in testing frameworks. Cons: When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly. More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure. The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions! Decision: On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden. Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. There is an exception to this rule (no pun intended) for Windows code. Run-Time Type Information (RTTI) link ▶We do not use Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++ class of an object at run time. Pros: It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. In rare circumstances, it is useful even outside of tests. Cons: A query of type during run-time typically means a design problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the design of your class. Decision: Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type. Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself. If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system. If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Casting link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);. Definition: C++ introduced a different cast system from C that distinguishes the types of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., (int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them. Cons: The syntax is nasty. Decision: Do not use C-style casts. Instead, use these C++-style casts. Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier (see const). Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues. Do not use dynamic_cast except in test code. If you need to know type information at runtime in this way outside of a unittest, you probably have a design flaw. Streams link ▶Use streams only for logging. Definition: Streams are a replacement for printf() and scanf(). Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering (the %1s directive), which is helpful for internationalization. Decision: Do not use streams, except where required by a logging interface. Use printf-like routines instead. There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons. Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams. cout << this; // Prints the address cout << *this; // Prints the contents The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason. Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover? cerr << "Error connecting to '" hostname.first << ":" hostname.second << ": " hostname.first, foo->bar()->hostname.second, strerror(errno)); And so on and so forth for any issue you might bring up. (You could argue, "Things would be better with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.) Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write. Preincrement and Predecrement link ▶Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English. Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment. Use of const link ▶We strongly recommend that you use const whenever it makes sense to do so. Definition: Declared variables and parameters can be preceded by the keyword const to indicate the variables are not changed (e.g., const int foo). Class functions can have the const qualifier to indicate the function does not change the state of the class member variables (e.g., class Foo { int Bar(char c) const; };). Pros: Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs. Cons: const is viral: if you pass a const variable to a function, that function must have const in its prototype (or the variable will need a const_cast). This can be a particular problem when calling library functions. Decision: const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it makes sense to do so: If a function does not modify an argument passed by reference or by pointer, that argument should be const. Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member. Consider making data members const whenever they do not need to be modified after construction. However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately describes how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient. The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Where to put the const Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the object it's describing. However, this consistency argument doesn't apply in this case, because the "don't go crazy" dictum eliminates most of the uses you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int). That said, while we encourage putting const first, we do not require it. But be consistent with the code around you! Integer Types link ▶Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from , such as int16_t. Definition: C++ does not specify the sizes of its integer types. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits. Pros: Uniformity of declaration. Cons: The sizes of integral types in C++ can vary based on compiler and architecture. Decision: defines types like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer types, only int should be used. When appropriate, you are welcome to use standard types like size_t and ptrdiff_t. We use int very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use int64_t or uint64_t. For integers we know can be "big", use int64_t. You should not use the unsigned integer types such as uint32_t, unless the quantity you are representing is really a bit pattern rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this. On Unsigned Integers Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider: for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect. So, document that a variable is non-negative using assertions. Don't use an unsigned type. 64-bit Portability link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment. printf() specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file inttypes.h): // printf macros for size_t, in the style of inttypes.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else #define __PRIS_PREFIX #endif // Use these macros after a % in a printf format string // to get correct 32/64 bit behavior, like this: // size_t size = records.size(); // printf("%"PRIuS"\n", size); #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" Type DO NOT use DO use Notes void * (or any pointer) %lx %p int64_t %qd, %lld %"PRId64" uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64" size_t %u %"PRIuS", %"PRIxS" C99 specifies %zu ptrdiff_t %d %"PRIdS" C99 specifies %zd Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x). Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a pointer-sized integer. You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class/structure with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()). Use the LL or ULL suffixes a
二级减速器课程设计说明书,全英文书写 《Machine Parts Design》 Design Specification Topic Designation of Reducer College College of Mechanical and Electrical Engineering Major Mechanical Engineering Class 16机械工程3(国际化) No. of team Team 1 ID/Name 陈旭颖 16211452104 方 琢 16211452105 李成雍 16211452106 Instructor Zhang Yi Date submitted 2019.01.11 Contents Abstract 1 Chapter 1 Course Design Task Book 3 1.1 Purpose 3 1.2 Description of design project 3 1.3 Design Data 4 Chapter 2 Integral Design Scheme of Transmission Device 4 2.1 Transmission Scheme 4 2.2 Advantages and Disadvantages of this Scheme 4 Chapter 3 Selection of Motor 5 3.1 Motor Type Selection 5 3.2 Determination of the Efficiency of the Transmission 5 3.3 Selection of the motor capacity 5 3.4 Determination of the total transmission ratio and distribution transmission ratio of the transmission device 7 Chapter 4 Calculation of Dynamic Parameters 8 Chapter 5 Designation and calculation of high speed gear 11 5.1 Selection of gear type, accuracy grade, material and number of teeth 11 5.2 Design according to tooth surface contact fatigue strength 11 5.3 Determination of the sizes of transmission 15 5.4 Check the bending fatigue strength of tooth root 15 5.5 Calculations of other geometric dimensions of gear transmission 19 5.6 Summary of gear parameters and geometric dimensions 20 Chapter 6 Calculation of low-speed gear 21 6.1 Selection of gear type, accuracy grade, material and number of teeth 21 6.2 Designation according to tooth surface contact fatigue strength 22 6.3 Determination of the sizes of transmission 25 6.4 Check the bending fatigue strength of tooth root 26 6.5 Calculations of other geometric dimensions of gear transmission 30 6.6 Summary of gear parameters and geometric dimensions 30 Chapter 7 The designation of the shaft 32 7.1 Calculateion of High-speed shaft design 32 7.2 Calculation of jack shaft design 39 7.3 Calculation of low speed shaft 47 Chapter 8 Rolling bearing life check 53 8.1 Bearing check on high speed shaft 53 8.2 Bearing check on the jack shaft 55 8.3 Bearing check on the low speed shaft 57 Chapter 9 Key connection design calculation 58 9.1 Calculation check of coupling key connection 58 9.2 Calculation check of low speed pinion’s key connection 59 9.3 Calculation check of high speed main gear’s key connection 59 9.4 Calculation check of low speed main gear’s key connection 59 Chapter 10 Coupling selection 60 10.1 Coupling on the high speed shaft 60 10.2 Coupling on the low speed shaft 60 Chapter 11 Seal and lubricate the reducer 61 11.1 Selection of sealing 61 11.2 Gear lubrication 61 11.3 Bearing lubrication 62 Chapter 12 Reducer accessory 63 12.1 Oil level indicator 63 12.2 Ventilator 63 12.3 Drain plug 64 12.4 Peephole cover 65 12.5 Positioning pin 66 12.6 Cover screw 67 12.7 Lifting device 68 Chapter 13 Main structural dimensions of reducer housing 70 Chapter 14 Drawing of structure analysis of reduce 72 14.1 Drawing of assembly 72 14.2 Housing 73 14.3 Drawing of gears 74 14.4 Drawing of shafts 78 Chapter 15 Conclusion 81 15.1 Summary 81 15.2 Job description of team members 82 Reference 83 Attachment 84 Abstract Belt conveyor is a kind of friction driven to transport materials in a continuous way machinery. It Is mainly composed of irame conveyor belt, supporting roller, roller, tensioning device and belt conveyor motor device. It can put the material on a certain conveying line and form a conveying process of material from the initial feeding point to the final unloading point. It can not only carry out the transport of broken bulk materials, but also the transport of finished articles. In addition to the pure material transport, it can also cooperate with the requirements of the technological process in the production process of various industrial enterprises to form a rhythmic assembly line. Belt conveyor is widely used in metallurgy, coal, transportation, water and electricity, chemical and other departments, because it has a large amount of transport, simple structure, convenient maintenance, low cost, strong versatility and other advantages. Belt conveyor is also used in building materials, power, light industry, food, ports, ships and other departments. Main contents of this manual is for the design of belt conveyor drive system, the V belt transmission and twoestage cylindrical gear reducer, used in the design and calculation to the "machine design foundation", "mechanical drawing" "tolerance and interchangeability", “theoretical mechanics" courses, such as knowledge, and use AutoCAD software to carry on the drawing, so the comprehensive practice is a very important link, is also a comprehensive, standardized training in practice. Through this training, so that we have been in many aspects of training and training. It is mainly reflected in the following aspects. (1) we have cultivated the design idea of combining theory with practice, trained our ability to comprehensively apply the basic theory of mechanical design course and other related courses, analyze and solve practical engineering problems in combination with production practice, and consolidated, deepened and expanded the knowledge of relevant mechanical design. (2) through the standard mechanical parts. common mechanical transmission or simple mechanical design, so that we master the general mechanical design procedures and methods. establish a correct engineering desrgn Ideas. cultivate independence. comprehensive. Scientific engineering design ability and innovation ability. (3) in addition, it cultivates our ability to consult and use manuals, atlas and other relevant technical data, as well as the ability in calculation, drawing data processing and computer, aided design. (4) enhanced our understanding and application of the functions of Word and AutoCAD in office software. Keywords: reducer, transmission device, design, calculation, CAD Chapter 1 Course Design Task Book 1.1 Purpose According to the diagam of the belt conveyor system: (1) Plan and analysis of transmission device; (2) Selection of motor and calculation of kinematic and dynamic parameters in conveyor system; (3) Design of transmission parts (e.g. gear, worm or belt, etc.); (4) Design of shaft; (5) Design of bearing and its assemblies; (6) Selection and confirmation of key and coupling; (7) Design of lubrication; (8) Housing, framework and accessories; (9) Drawing of assembly and its components; (10) Design specification 1.2 Description of design project (a) running on two shifts per day in one-direction continuously; (b) stable loading; (c) starting with idling; (d) indoor setting with dust; (e) usage period: 10 years, minor overhaul period: 1 year, and overhaul period: 3 years; (f) power source is alternating three-phase voltage; (g) small-batch production in medium scale machinery plant; (h) allowed tolerance of conveyor speed is ± 5%. Working hours per day: 16 hours, working life: 10 years, working days per year: 300 days, equipped with three-phase AC power supply, voltage 380/220 V. 1.3 Design Data Working force of conveyor, F 2900N Speed of conveyor, v 1.5m/s Diameter, D 410mm Chapter 2 Integral Design Scheme of Transmission Device 2.1 Transmission Scheme Analysis of transmission scheme v-belt transmission is adopted . Considering the requirements of the project , I chose this scheme . Its transmission diagram is shown in figure 1-1. The transmission scheme has been given, and the reducer is a two-stage cylindrical gear reducer. 2.2 Advantages and Disadvantages of this Scheme The extemal outline size of this scheme is large, with good shock absorption capacity, low manufacturing, stability accuracy with low cost, and overload protection. But because the gear relative to the bearing of the two-stage cylindrical gear reducer is arranged asymmetrically, the load distribution along the tooth direction is uneven, and the shaft stiffness is required. Chapter 3 Selection of Motor 3.1 Motor Type Selection According to the use of the Y-series general purpose fully closed self-cooled three-phase asynchronous motor. 3.2 Determination of the Efficiency of the Transmission According to table 2-1, we got: The Efficiency of coupling:η1=0.99 The Efficiency of rolling bearing:η2=0.99 The Efficiency of closed cylindrical gears:η3=0.98 The Efficiency of Working Machine:ηw=0.97 Total efficiency from motor to machine: ηa=η1×η24×η32×ηw=0.877 3.3 Selection of the motor capacity The power required by the working machine Pw: Rated power required by motor Pd: Work speed of transmission belt wheels nw: According to the recommended reasonable transmission ratio range in table 2-2, the transmission ratio range of the expanded two-stage gear reducer ia=8 ~ 40, the transmission ratio range of v-belt transmission is ib=2~4, so the theoretical transmission ratio range is=16~160. The optional speed range of the motor : nd=is*nw=(16 ~ 160) 69.91=559--2796r/min. After comprehensive consideration of price, weight, transmission ratio and other factors, the selected three-phase asynchronous motor model : Y132M2-6 . Rated power Pen=5.5kW,Full load speed nm=960r/min,Synchronous speed nt=1000r/min。 Serial Number Motor Type Synchronous Speed/(r/min) Rated Power/kW Full Speed/(r/min) 1 Y160M2-8 750 5.5 720 2 Y132M2-6 1000 5.5 960 3 Y132S-4 1500 5.5 1440 4 Y132S1-2 3000 5.5 2900 Figure 3-1 main size parameters of the motor Height of Center Dimensionof overall Dimensionof base mounting Diameter of anchor bolt hole Size of Axis stretch Size of key H L×HD A×B K D×E F×G 132 515×315 216×178 12 38×80 10×33 3.4 Determination of the total transmission ratio and distribution transmission ratio of the transmission device (1)Calculation of total transmission ratio According to the selected fullload speed of the motor nm and the drive shaft speed of the motor nw,we can calculate the total transmission ratio of the transmission device ia: (2)Allocate transmission ratio High speed stage transmission ratio i1 Then the transmission ratio of low-speed stage i2 Total transmission ratio of reducer ib Chapter 4 Calculation of Dynamic Parameters (1)The speed of each shaft: High speed shaft : Jack shaft : Low speed shaft : The working machine shaft : (2)Input power of each shaft: High speed shaft : Jack shaft : Low speed shaft : The working machine shaft : Then the output power of each shaft: High speed shaft : Jack shaft : Low speed shaft : The working machine shaft : (3)Input torque of each shaft: Motor shaft : High speed shaft : Jack shaft : Low speed shaft : The working machine shaft : Then the torque of each shaft: High speed shaft : Jack shaft : Low speed shaft : The working machine shaft : The rotational speed, power and torque of each shaft are listed in the following table name of the shaft rotating speed n /(r/min) power P/kW torque T/(N•m) Motor shaft 960 4.96 49.34 High speed shaft 960 4.91 48.84 Jack shaft 222.74 4.76 204.09 Low speed shaft 69.82 4.62 631.92 The working machine shaft 69.82 4.35 594.99 Chapter 5 Designation and calculation of high speed gear 5.1 Selection of gear type, accuracy grade, material and number of teeth 1. According to the transmission scheme, helical cylindrical gear transmission is selected,Pressure angle α=20°,Primary spiral Angle β=12°。 2. Refer to table 10-6 for level 7 accuracy. 3. Material selection : According to table 10-1, Pinion chosen: 40Cr (quenched and tempered), hardness: 280HBS; Main gear: 45 (quenched and tempered), hardness: 240HBS. 4. Number of pinion teeth: z1=24,number of main gear teeth: z2=z1×i=24×4.31=103. 5.2 Design according to tooth surface contact fatigue strength 1. The diameter of the dividing circle of the pinion is calculated by formula (10-24),that is: (1) Determine the values of each parameter in the formula (1) Choose KHt=1.3 (2) Calculate the torque T transmitted by the pinion: (3) According to table 10-7, the tooth width coefficient: φd=1 (4) According to figure 10-20, regional coefficient: ZH=2.47 (5) According to table 10-5, the elastic influence coefficient of the material: ZE=189.8√MPa. (6)The contact fatigue strength Zε is calculated by formula (10-9). (7) The spiral Angle coefficient Zβ can be obtained from the formula. (8) Calculate the allowable contact fatigue stress[σH] According to figure 10-25d, the contact fatigue limit of pinion and large gear is respectively The stress cycle number is calculated from equation (10-15): Contact fatigue coefficients were obtained from FIG. 10-23 If the failure probability is 1% and the safety coefficient S=1,then: Take the smaller one of [σH]1 and [σH]2as the contact fatigue allowable stress of the gear pair, that is: (2) Calculate the diameter of the dividing circle of the pinion 2. Adjust the diameter of the dividing circle of the pinion (1) Data preparation before calculating actual load coefficient. (1) Circumferential velocity ν (2) Tooth width b (2) Calculate the actual load coefficient KH (1) According to table 10-2, KA=1 (2) According to v=1.827m/s and the accuracy of level 7, the dynamic load coefficient can be obtained from figure 10-8, Kv=1.035 (3) The circular force of a gear. In table 10-3, the load distribution coefficient between teeth was KH =1.4 When the accuracy of level 7 and the relative support of pinion are arranged asymmetrically by interpolation method, according to table 10-4, the distribution coefficient of load in tooth direction KHβ=1.417 Thus, the actual load coefficient KH is obtained (3) According to equation (10-12) and the actual load coefficient, the diameter of the dividing circle d1 can be obtained (4) Determine the modulus of 5.3 Determination of the sizes of transmission 1. Computing center distance a 2. The helix Angle is corrected according to the center distance after rounding β=12°19'58" 3. Calculate the dividing circle diameter d1 ,d2of small and big gear 4. Calculate the tooth width b Take B1=55mm, B2=50mm 5.4 Check the bending fatigue strength of tooth root The fatigue strength condition of tooth root bending: (1)T、mn and d1 are like the previous Tooth width: b=b2=50 Tooth shape coefficient YFa and stress correction coefficient YSa, the equivalent number of teeth: The equivalent number of teeth of pinion Zv1: Equivalent number of teeth of main gear Zv2: The tooth shape coefficient is obtained from FIG. 10-17 The stress correction coefficient is obtained from FIG. 10-18 (1) Choose load factor KFt=1.3 (2) From equation (10-18), the coincidence coefficient of bending fatigue strength Yε can be calculated Have a type: (3) From equation (10-19), obtain the spiral Angle coefficient of bending fatigue strength Yβ (2) Circumferential velocity (3) Aspect ratio b/h According to v=2.47m/s, level 7 accuracy, dynamic load coefficient can be found from figure 10-8, Kv=1.047 According to table 10-3 , load distribution coefficients between teeth KFα=1.4 According to table 10-4, KH =1.42 and b/h=50/4.5=11.111. According to figure 10-13, KF =1.079. Then the load coefficient is: According to FIG. 10-24c, the tooth root bending fatigue limit of pinion and big gear is respectively The bending fatigue coefficient KFN1 ,KFN2 was obtained from FIG. 10-22 The bending fatigue safety factor S=1.25, from equation (10-14) Check the bending fatigue strength of tooth root The bending fatigue strength of tooth root meets the requirement, and the ability of pinion to resist bending fatigue damage is greater than that of large gear. (4) The circular velocity of a gear Level 7 accuracy is appropriate. 5.5 Calculations of other geometric dimensions of gear transmission (1)Calculate the height of addendum tooth, dedendum tooth and total tooth (2)Calculate the addendum circle diameters of small and large gears (3)Calculate the diameter of dedendum circle of small and large gears 5.6 Summary of gear parameters and geometric dimensions Code name Calculated formula Pinion Main gear Modulus m 2 2 Spiral Angle β left-handed 12°19'58" right-handed 12°19'58" Coefficient of addendum height ha* 1.0 1.0 Tip clearance coefficient c* 0.25 0.25 Number of teeth z 24 103 Width of teeth B 55 50 Height of addendum teeth ha m×ha* 2 2 Height of dedendum teeth hf m×(ha*+c*) 2.5 2.5 Diameter of the dividing circle d 49.134 210.866 Addendum circle diameter da d+2×ha 53.134 214.866 Dedendum circle diameter df d-2×hf 44.134 205.866 Figure 5-1 structure diagram of high-speed main gear Chapter 6 Calculation of low-speed gear 6.1 Selection of gear type, accuracy grade, material and number of teeth 1. According to the transmission scheme, choose helical cylindrical gears,The pressure off for alpha = 20 °, primary spiral Angle beta = 12 °. 2. Refer to table 10-6 , choose level 7 accuracy. 3. Material selection According to table 10-1, choose pinion 40Cr (quenching and tempering), and the hardness was 280HBS; choose main gear 45 (quenching and tempering), and the hardness was 240HBS 4. Select the number of pinion teeth z1=25, then the number of large gear teethz2=z1×i=25×3.19=81. 6.2 Designation according to tooth surface contact fatigue strength 1. From formula (10-24), the diameter of the dividing circle of the pinion is calculated, i.e (1) Determine the values of each parameter in the formula (1) Choose KHt=1.3 (2) Calculate the torque transmitted by the pinion: (3) From table 10-7, the tooth width coefficient is φd=1 (4) From figure 10-20, Regional coefficient ZH=2.47 (5) From table 10-5, the elastic influence coefficient of the material ZE=189.8√MPa。 (6) From equation (10-9), the coincidence coefficient is used to calculate the contact fatigue strength Zε. (7) From the formula, the spiral Angle coefficient Zβ. (8) Calculate the allowable contact fatigue stress[σH] According to figure 10-25d, the contact fatigue limit of pinion and big gear is respectively From equation (10-15) , the number of stress cycles can be calculated : From figure10-23, check the contact fatigue coefficient If the failure probability is 1% and the safety coefficient S=1, then Take the smaller one of [σH]1 and [σH]2as the contact fatigue allowable stress of the gear pair, that is: (2) Calculate the diameter of the dividing circle of the pinion 2.Adjust the diameter of the dividing circle of the pinion (1) Data preparation before calculating actual load coefficient. (1) Circumferential velocity ν (2) Tooth width b (2) Calculate the actual load coefficient KH (1) According to table 10-2, KA=1 (2) According to v=0.666m/s and the accuracy of level 7, the dynamic load coefficient can be obtained from figure 10-8, Kv=1.013 (3) The circular force of a gear. In table 10-3, the load distribution coefficient between teeth was KH =1.2 When the accuracy of level 7 and the relative support of pinion are arranged asymmetrically by interpolation method, according to table 10-4, the distribution coefficient of load in tooth direction KHβ=1.421 Thus, the actual load coefficient KH is obtained (3) According to equation (10-12) and the actual load coefficient, the diameter of the dividing circle d1 can be obtained (4) Determine the modulus of 6.3 Determination of the sizes of transmission 1. Computing center distance a 2.The helix Angle is corrected according to the center distance after rounding β=12°43'9" 3. Calculate the dividing circle diameter d1 ,d2of small and big gear 4. Calculate the tooth width b Take B1=85mm B2=80mm 6.4 Check the bending fatigue strength of tooth root The fatigue strength condition of tooth root bending: (1)T、mn and d1 are like the previous Tooth width: b=b2=80 Tooth shape coefficient YFa and stress correction coefficient YSa, the equivalent number of teeth: Equivalent number of teeth of pinion Zv1: Equivalent number of teeth of main gear Zv2: The tooth shape coefficient is obtained from FIG. 10-17 The stress correction coefficient is obtained from FIG. 10-18 (1) Choose load factor KFt=1.3 (2) From equation (10-18), the coincidence coefficient of bending fatigue strength Yε can be calculated Have a type: (3) From equation (10-19), obtain the spiral Angle coefficient of bending fatigue strength Yβ (2) Circumferential velocity (3) Aspect ratio b/h According to v=0.9m/s, level 7 accuracy, dynamic load coefficient can be found from figure 10-8, Kv=1.017 According to table 10-3 , load distribution coefficients between teeth KFα=1.4 According to table 10-4, KHβ =1.427 and b/h=80/6.75=11.852. According to figure 10-13, KF =1.08. Then the load coefficient is: According to FIG. 10-24c, the tooth root bending fatigue limit of pinion and big gear is respectively The bending fatigue coefficient KFN1 ,KFN2 was obtained from FIG. 10-22 The bending fatigue safety factor S=1.25, from equation (10-14) Check the bending fatigue strength of tooth root The bending fatigue strength of tooth root meets the requirement, and the ability of pinion to resist bending fatigue damage is greater than that of large gear. (4) The circular velocity of a gear Level 7 accuracy is appropriate. 6.5 Calculations of other geometric dimensions of gear transmission (1)Calculate the height of addendum tooth, dedendum tooth and total tooth (2)Calculate the addendum circle diameters of small and large gears (3)Calculate the diameter of dedendum circle of small and large gears 6.6 Summary of gear parameters and geometric dimensions Code name Calculated formula Pinion Main gear Modulus m 3 3 Spiral Angle β left-handed 12°43'9" right-handed 12°43'9" Coefficient of addendum height ha* 1.0 1.0 Tip clearance coefficient c* 0.25 0.25 Number of teeth z 25 81 Width of teeth B 85 80 Height of addendum teeth ha m×ha* 3 3 Height of dedendum teeth hf m×(ha*+c*) 3.75 3.75 Diameter of the dividing circle d 76.887 249.113 Addendum circle diameter da d+2×ha 82.887 255.113 Dedendum circle diameter df d-2×hf 69.387 241.613 Figure 6-1 Low speed large gear structure drawing Chapter 7 The designation of the shaft 7.1 Calculateion of High-speed shaft design 1. Select the material on the shaft and determine the allowable stress Because the reducer is a general machine, there is no special requirement, so 40Cr (quenched and tempered) is selected, the hardness is 280HBS, check the table15-1,take σb=735MPa, σ-1b=60MPa 2. The minimum diameter of the shaft estimated according to the initial torsion strength Check table 15-3, take A0=112,so Shaft ends have 1 keyway, therefore, the axle diameter should be increased by 5% According to the table, the diameter of the standard axle hole is 22mm, so d=22 Figure 7-1 Schematic diagram of high-speed shaft (1) The minimum diameter of the input shaft is obviously d12, where the coupling is mounted. In order to adapt the selected shaft diameter d12 to the coupling aperture, the type of coupling should be selected. The calculated torque of the coupling Tca = KA×T, according to the table, thinking about the stability, we choose KA = 1.3, then: According to the condition that the torque Tca of the coupling should be less than the nominal torque of the coupling, refer to standard GB t4323-2002 or design manual, choose LX3 type coupling. The aperture of the semi-coupling is 22mm, the hub hole length of the semi-coupling and the shaft is 52mm. Choose ordinary flat keys,A type keys, b×h = 6×6mm(GB T 1096-2003), bond length L=40mm。 (2) Initial selection of rolling bearing. Since the bearing is subject to both radial and axial forces, angular contact bearing is selected. Referring to the work requirements and according to d23 = 27mm, select 7206AC angular contact bearing from bearing product catalog, its size: d×D×B = 30×62×16mm, so d34 = d78 = 30 mm. The positioning shaft shoulder height of 7206AC type bearing is found in the manual, h = 3 mm,then choose d45 = d67 = 36 mm. (3)Because the diameter of the gear is small, in order to ensure the strength of the gear wheel body, the gear and the shaft should be made into one and become the gear shaft. So l56 = 55 mm, d56 = 53.134 mm. (4) Thickness of bearing end covere=10, thickness of the gasketΔt=2. According to the bearing end cover for easy assembly and disassembly, ensure that the outer end face of the bearing end cover has a certain distance from the end face of the coupling, K=24; Screw C1=22mm, C2=20mm, thickness of box seat wall δ=8mm, then: (5) Take small spacing distance of enclosure wall Δ1 = 10 mm, the distance between high speed main gear and low speed pinion Δ3 = 15 mm distance. Considering about the housing casting error, when determining the position of rolling bearing, a distance Δ from inner wall of box should be taken, take Δ = 10 mm, the width of low speed pinion b3=85mm, then: At this point, the diameter and length of each section of the shaft have been preliminarily determined. Shaft section 1 2 3 4 5 6 7 Diameter / mm 22 27 30 36 53.134 36 30 Length/ mm 52 65 28 105.5 55 8 28 3. Stress analysis of the shaft The circumferential force on a high speed pinion Ft1 (d1 is the diameter of the indexing circle of the high-speed pinion) Radial force on a high speed pinion Fr1 Axial force on a high speed pinion Fa1 According to 7206AC angular contact manual, pressure center a=18.7mm Distance between the center point of the first shaft and the bearing pressure center l1: Distance from bearing pressure center to gear fulcrum l2: Distance between gear midpoint and bearing pressure center l3: (1) Calculate the supporting reaction of the shaft Horizontal support reaction: Vertical support reaction: (2) Calculate the bending moment of the shaft, and draw the bending moment diagram The horizontal bending moment at section C: The vertical bending moment at section C: Bending moment diagram of horizontal plane (fig.b) and vertical plane (fig.c). The resultant bending moment at section C: (3) Make composite bending moment diagram (figure d) Make torque diagram (figure e) Figure 7-2 High - speed shaft force and bending moment diagram 4. Check the strength of the shaft Because the bending moment on the left side of C is large and the action has torque, the left side of C is the dangerous section. The bending section coefficient W: The torsion cross section coefficient WT: The maximum bending stress: The shear stress: Check and calculate according to the strength of bending and torsion. For the shaft of one-way drive, torque is processed according to pulsating cycle. Therefore, the reduced coefficient is adopted α=0.6, then the equivalent stress is (10) Check the table, get 40Cr(tempering and tempering) treatment, and the limit of tensile strength σB=735MPa; Then the allowable bending stress of the axis [σ-1b]=60MPa, σca<[σ-1b], so the strength is good. 7.2 Calculation of jack shaft design 1. Select the material on the shaft, and determine the allowable stress Because the reducer is a general machine, there is no special requirements, so choose 45 (quenched and tempered), the hardness: 240HBS. Referring table 15-1, take σb=640MPa, σ-1b=60MPa 2. According to the initial torsion strength, the minimum diameter of the shaft estimated Refer to table 15-3, take A0=112, then: Since the minimum diameter of the shaft section is all rolling bearings, the standard diameter d=35mm is selected. Figure 7-3 Diagram of intermediate shaft (1) Initial selection of rolling bearing. The minimum diameters of the intermediate shaft are d12 and d56 for mounting the rolling bearing. Because the bearing is subject to both radial and axial forces, angular contact bearing is chosen. Referring to the requirement of working and according to dmin = 31.08 mm, from the bearing catalogue, selsct angular contact bearing 7207AC, its size: d×D×B = 35×72×17mm, so d12 = d56 = 35 mm. (2) At the installation of the big gear, take the diameter of the shaft section d45 = 38mm; Positioning by oil baffle ring is taken between the right end of the gear and the right bearing. It is known that the width of the hub of the high-speed large gear wheel b2 = 50mm, in order to press gears reliably, this section should be slightly shorter than the width of the hub, then take l45 = 48 mm. Shaft shoulder positioning is adopted in the left end of the gear, the height of shaft shoulder h = (2~3)R. Refer to the table with trunnion d45 = 38 mm, take h = 5 mm, then the diameter of Collar point d34 = 48 mm. Collar width b≥1.4h, take l34 = 15 mm. (3) Left end rolling bearing adopts oil baffle ring for axial positioning. (4) Considering about material and machining economy, low speed pinion and shaft should be designed and manufactured separately. It is known that the hub width of the low-speed pinion is b3= 85mm, in order to make the end face of oil retaining ring press the gear reliably, this section should be slightly shorter than the width of the hub, so take l23 = 83 mm,d23=38mm。 (5) Take the distance between the low-speed pinion and the inner wall of the boxΔ1 =10 mm, the distance between the high speed big gear and the inner wall of the box Δ2 =12.5 mm, the distance between high speed main gear and low speed pinionΔ3=15mm. Consider housing casting error, when determining the position of rolling bearing, should be from a distance Δ casing wall, take Δ = 10 mm, then: At this point, the diameter and length of each section of the shaft have been preliminarily determined. Shaft section 1 2 3 4 5 Diameter/ mm 35 38 48 38 35 Length/ mm 39 83 15 48 41.5 3. Force analysis of the shaft The circumferential force on a high speed pinion Ft2 (d2 is the diameter of the indexing circle of the high-speed pinion) Radial force on a high speed pinion Fr2 Axial force on a high speed pinion Fa2 Circumferential force on the low-speed pinion Ft3 (d3 is the dividing circle diameter of the low-speed pinion) Radial force on a low speed pinion The axial force on a low speed pinion According to 7207AC angular contact manual, pressure center a=21mm Distance from bearing pressure center to middle point of low-speed pinion: Distance from the midpoint of the low-speed pinion to that of the high-speed large gear: Distance from the middle point of the high-speed large gear to the bearing pressure center: (1) Calculate the reaction force of the shaft Horizontal support reaction Vertical support reaction (2) Calculate the bending moment of the shaft and draw the bending moment diagram The horizontal bending moment at section B The horizontal bending moment at section C The vertical bending moment at section C The vertical bending moment at section B Draw the bending moment diagram of horizontal plane (fig.b) and vertical plane (fig.c) The resultant bending moment at section B The synthetic bending moment of section C: Make composite bending moment diagram (figure d) Make torque diagram (figure e) Figure 7-4 force and bending moment of jack shaft 4. Check the strength of the shaft Because the bending moment on the left side of B is large and the action has torque, the left side of B is the dangerous section. Its bending section coefficient: Its torsion cross section coefficient: The maximum bending stress: Its shear stress: Check and calculate according to the strength of bending and torsion. For the shaft of one-way drive, torque is processed according to pulsating cycle. Therefore, the reduced coefficient is adopted α=0.6, then the equivalent stress is Check the table, get 40Cr(tempering and tempering) treatment, and the limit of tensile strength σB=640MPa; Then the allowable bending stress of the axis [σ-1b]=60MPa, σca<[σ-1b], so the strength is good. 7.3 Calculation of low speed shaft 1. Select the material on the shaft, and determine the allowable stress Because the reducer is a general machine, there is no special requirements, so choose 45 (quenched and tempered), the hardness: 240HBS. Referring table 15-1, take σb=640MPa, σ-1b=60MPa 2. According to the initial torsion strength, the minimum diameter of the shaft estimated Refer to table 15-3, take A0=112, then: Shaft end has 1 keyway, so increase shaft diameter by 7% According to the table, the diameter of the standard axle hole is 50mm, so d=50 Figure 7-5 Schematic diagram of low-speed shaft (1) The minimum diameter of the output shaft is obviously the diameter d1 of the shaft where the coupling is mounted. In order to make the selected shaft diameter d1 match the coupling aperture, it is necessary to select the type of coupling.The calculated torque of the coupling Tca = KA×T, refer to the table, consider about stability, then take KA = 1.3,thus: According to the condition that the torque Tca of the coupling should be less than the nominal torque of the coupling, check the standard GB t4323-2002 or the design manual, choose LX4 type coupling. The aperture of the semi-coupling is 50mm, the hub hole length of fitness of the semi-coupling and the shaft is 112mm. Choose ordinary flat bond, A type bond, b×h = 14×9mm(GB T 1096-2003), length of bond L=100mm. (2) Initial selection of rolling bearing. Because the bearing is subject to both radial and axial forces, angular contact bearing is chosen. According to work requirements and d23 = 55mm, angular contact bearing 7212AC is selected from the bearing product catalog, its size: d×D×B = 60×110×22mm, so d34 = d78 = 60 mm. Positioning of bearing oil retaining ring. According to the manual, the positioning shaft shoulder height of type 7212AC bearing is h = 4.5mm, so d45 = 69mm (3) Take the diameter of the shaft section where the gear is mounted d67 = 63 mm;The width of the low-speed large gear hub is known as b4 = 80 mm,in order to make the end face of the oil retaining ring press the gear reliably, this shaft segment should be slightly shorter than the width of the hub, so l67 = 78mm. The left end of the gear is fixed by the shaft shoulder. The height of shaft shoulder h = (2~3)R,The diameter of the shaft d67 = 63 mm, so take h = 10 mm, then the diameter at the collar d56 = 83 mm, take l56=10mm. (4) Thickness of bearing end cover e=10, the thickness of the gasket Δt=2. According to the ease of mounting and dismounting of the bearing end cover, ensure that the outer end face of the bearing end cover has a certain distance from the end face of the coupling K=24, screw C1=22mm, C2=20mm, box seat wall thickness δ=8mm, then: (5) Assume the distance between low level main gear and inner box wall Δ 2 = 12.5 mm, the distance between high speed main gear and low speed pinion Δ 3 = 15 mm distance. Consider housing casting error, when determining the position of rolling bearing, should be from a distance Δ casing wall, assume Δ = 10 mm, then: At this point, the diameter and length of each section of the shaft have been preliminarily determined. Shaft section 1 2 3 4 5 6 7 Diameter 50 55 60 69 83 63 60 Length 112 59 44.5 57.5 10 78 46.5 3. Force analysis of the shaft Circumferential force on the low-speed big gear (d4 is the dividing circle diameter of the low-speed big gear) The radial force on a large low speed gear The axial force exerted on a large low-speed gear Refer to the manual with 7212AC angular contaction, know pressure center a=30.8mm (1)Calculate the supporting reaction of the shaft Horizontal support reaction Vertical support reaction (2) Calculate the bending moment of the shaft and draw the bending moment diagram The horizontal bending moment at section C The vertical bending moment at section C Draw the bending moment diagram of horizontal plane (fig.b) and vertical plane (fig.c) The resultant bending moment at section C (3) Make composite bending moment diagram (figure d) Make torque diagram (figure e) Figure 7-6 Diagram of force and bending moment of low speed shaft 4. Check the strength of the shaft Because the bending moment on the left side of C is large and the action has torque, the left side of C is the dangerous section Its bending section coefficient: Its torsion cross section coefficient: The maximum bending stress: Its shear stress: Check and calculate according to the strength of bending and torsion. For the shaft of one-way drive, torque is processed according to pulsating cycle. So the reduced coefficient =0.6, then the equivalent stress: Refer to the the table, get 45(tempering) treatment, tensile strength limitσB=640MPa,then the allowable bending stress of the axis[σ-1b]=60MPa, σca<[σ-1b], so the strength is good. Chapter 8 Rolling bearing life check 8.1 Bearing check on high speed shaft Bearing code d(mm) D(mm) B(mm) Cr(kN) C0r(kN) 7206AC 30 62 16 22 14.2 Adopt 7206AC angular contact ball bearing, inner diameter d=30mm, outer diameter D=62mm, width B=16mm, Basic dynamic load rating Cr=22kN,Rated static load C0r=14.2kN. Life expectancy is Lh=48000h. According to the horizontal and vertical bearing reaction calculated previously, we can calculate the resultant bearing reaction: Axial force Fae=435N According to the calculations, bearing 1 is "pressed", while bearing 2 is “relaxing”. Refer to the table, X1=0.41,Y1=0.87,X2=1,Y2=0 Refer to the table, ft=1,fp=1 Then, take the bigger one into Bearing life is sufficient. 8.2 Bearing check on the jack shaft Bearing code d(mm) D(mm) B(mm) Cr(kN) C0r(kN) 7207AC 35 72 17 29 19.2 Adopt 7207AC angular contact ball bearing, inner diameter d=35mm, outer diameter D=72mm, width B=17mm, Basic dynamic load ratingCr=29kN, Rated static load C0r=19.2kN Life expectancy is Lh=48000h. According to the horizontal and vertical bearing reaction calculated previously, we can calculate the resultant bearing reaction: Axial force Fae=775N According to the calculations, bearing 1 is "pressed", while bearing 2 is “relaxing”. Refer to the table, X1=0.41,Y1=0.87,X2=1,Y2=0 Refer to the table, ft=1,fp=1 Then, take the bigger one into Bearing life is sufficient. 8.3 Bearing check on the low speed shaft Bearring code d(mm) D(mm) B(mm) Cr(kN) C0r(kN) 7212AC 60 110 22 58.2 46.2 Adopt 7212AC angular contact ball bearing, inner diameter d=60mm, outer diameter D=110mm, width B=22mm, Basic dynamic load rating Cr=58.2kN,Rated static load C0r=46.2kN Life expectancy is Lh=48000h。 According to the horizontal and vertical bearing reaction calculated previously, we can calculate the resultant bearing reaction: Axial force Fae=1145N According to the calculations, bearing 1 is "pressed", while bearing 2 is “relaxing”. Refer to the table, X1=0.41,Y1=0.87,X2=1,Y2=0 Refer to the table, ft=1,fp=1 Then, take the bigger one into Bearing life is sufficient. Chapter 9 Key connection design calculation 9.1 Calculation check of coupling key connection The chosen type of key is A-type: 6×6(GB/T 1096-2003) Working length of key: l=L-b=40-6=34mm Contact height of the hub keyway: k=h/2=3mm According to the material of the coupling which is 45 and the stability of loading, we can get [σp]=120MPa, then it’s compression strength is It meets the strength requirement. 9.2 Calculation check of low speed pinion’s key connection The chosen type of key is A-type: 10×8(GB/T 1096-2003) Working length of key: l=L-b=70-10=60mm Contact height of the hub keyway: k=h/2=4mm According to the material of the low speed pinion which is 40Cr and the stability of loading, we can get [σp]=120MPa, then it’s compression strength is It meets the strength requirement. 9.3 Calculation check of high speed main gear’s key connection The chosen type of key is A-type: 10×8(GB/T 1096-2003) Working length of key: l=L-b=36-10=26mm Contact height of the hub keyway: k=h/2=4mm According to the material of the high speed main gear which is 45 and the stability of loading, we can get [σp]=120MPa, then it’s compression strength is It meets the strength requirement. 9.4 Calculation check of low speed main gear’s key connection The chosen type of key is A-type: 18×11(GB/T 1096-2003) Working length of key: l=L-b=63-18=45mm Contact height of the hub keyway: k=h/2=5.5mm According to the material of the low speed main gear which is 45 and the stability of loading, we can get [σp]=120MPa, then it’s compression strength is It meets the strength requirement. Chapter 10 Coupling selection 10.1 Coupling on the high speed shaft (1)Calculate the load on the coupling Refer to the table, the load coefficient of the coupling is KA=1.3 Then calculate the torque is Tc=KA×T=1.3×48.84=63.5N•m (2)Select the type of coupling Primary coupling model is LX3 elastic pin coupling (GB/ t4323-2002). Refer to the table, Nominal torque Tn=1250N•m, Allowable speed[n]=4700r/min, thus: Tc=63.5N•mδ 12.5mm Case cover and seat rib thickness m1、m m1≈0.85×δ1、m≈0.85×δ 8mm、8mm Outer diameter of high speed bearing end cap D1 D+(5~5.5)d3;D--bearing outer diameter 102mm Outer diameter of end cover of jack bearing D2 D+(5~5.5)d3;D--bearing outer diameter 112mm Outer diameter of low speed bearing end cap D3 D+(5~5.5)d3;D--bearing outer diameter 150mm Chapter 14 Drawing of structure analysis of reduce 14.1 Drawing of assembly 14.2 Housing 14.3 Drawing of gears High speed main gear Low speed pinion 14.4 Drawing of shafts High speed shaft Jack speed shaft Low speed shaft Chapter 15 Conclusion 15.1 Summary After hard work, I finally finished the mechanical design course. In the process of this operation, I encountered many difficulties. The repeated calculation and the design scheme modification exposed my lack of knowledge and experience in this aspect in the early stage, and I learned the lesson of blind calculation. As for drawing assembly drawing and part drawing, due to sufficient preliminary calculation, the whole process took less than three days. During this period, I also received a lot of help from my classmates and teachers. Here I would like to express my most sincere thanks to them. Although the time of this assignment is long and the process is tortuous, for me, the biggest gain is the method and ability. The ability to analyze and solve problems. In the whole process, I found that what students like us most lack is experience, no perceptual knowledge, empty theoretical knowledge, and some things may be out of touch with the reality. In general, I think doing this type of homework is of great help to us. It requires us to systematically connect the relevant knowledge we have learned, expose our shortcomings and make improvements. Sometimes a person's power is limited, the wisdom of all people, I believe our work will be more perfect! Due to the limited time, there are many shortcomings in this design, such as the huge box structure and large weight. The gear calculation is not accurate enough and other defects, I believe, through this practice, I can avoid a lot of unnecessary work in the future design, have the ability to design a more compact structure, transmission more stable and accurate equipment. 15.2 Job description of team members Team leader: 陈旭颖 Finish the designation and calculation of transmission device, motor, dynamic parameters, rolling bearings, keys and couplings. Draw the CAD of assembly drawing and reducer housing drawing. Write the design specification. Team members: 方琢 Finish the designation and calculation of high speed gear, jack gear and low speed gear. Draw the CAD of high speed gear, jack gear and low speed gear. 李成雍 Finish the designation and calculation of high speed shaft, intermediate shaft and low speed shaft. Draw the CAD of high speed shaft, intermediate shaft and low speed shaft. Reference [1] Kunwoo Lee, Principles of CAD/CAM/CAE Systems, Pearson, Jan., 1999. [2] Chris McMahon and Jimmie Browne, CAD/CAM Principles, Practices and Manufacturing Management (2/e), Prentice Hall, July, 1999. [3] Andrew D. Dimarogonas, Machine Design - A CAD Approach, John Wiley & Sons, Dec. 2000. [4] E. Paul Degarmo, J. T. Black and Ronald A. Kohser, Materials and Processes in Manufacturing (11th edition), Wiley, Dec. 2011. [5] 李育锡. 机械设计课程设计(第⼆版). 北京:⾼等教育出版社. in Chinese [6] 陈秀宁. 机械设计课程设计(第四版). 杭州:浙江⼤学出版社. 2010. in Chinese [7] 吴宗泽. 机械设计课程设计. 北京:⾼等教育出版社. 2007. in Chinese [8] 闻邦椿. 机械设计⼿册 1-6 卷(第五版). 北京:机械⼯业出版社. 2011. in Chinese Attachment 1.The drawing of assembly; 2.The drawing of reducer housing; 3.The drawing of pinion; 4.The drawing of main gear; 5.The drawing of low speed shaft; 6.The drawing of jack shaft; 7.The drawing of high speed shaft;
Acknowledgments xiii Introduction xv 1. Making Games the Modular Way 1 1.1 Important Programming Concepts.....................................2 1.1.1 Manager and Controller Scripts...............................2 1.1.2 Script Communication.......................................3 1.1.3 Using the Singleton Pattern in Unity...........................5 1.1.4 Inheritance.................................................6 1.1.5 Where to Now?.............................................8 2. Building the Core Game Framework 9 2.1 Controllers and Managers............................................11 2.1.1 Controllers................................................11 2.1.2 Managers.................................................11 2.2 Building the Core Framework Scripts..................................11 2.2.1 BaseGameController.cs.....................................12 2.2.1.1 Script Breakdown................................14 viii Contents 2.2.2 Scene Manager.............................................17 2.2.2.1 Script Breakdown................................17 2.2.3 ExtendedCustomMonoBehavior.cs...........................19 2.2.4 BaseUserManager.cs........................................20 2.2.4.1 Script Breakdown................................22 2.2.5 BasePlayerManager.cs.......................................22 2.2.5.1 Script Breakdown................................23 2.2.6 BaseInputController.cs......................................24 2.2.6.1 Script Breakdown................................26 3. Player Structure 29 3.1 Game-Specific Player Controller......................................31 3.2 Dealing with Input..................................................32 3.3 Player Manager.....................................................35 3.3.1 Script Breakdown..........................................36 3.4 User Data Manager (Dealing with Player Stats Such as Health, Lives, etc.)....37 3.4.1 Script Breakdown..........................................39 4. Recipes: Common Components 41 4.1 Introduction.......................................................41 4.2 The Timer Class....................................................43 4.2.1 Script Breakdown..........................................45 4.3 Spawn Scripts......................................................48 4.3.1 A Simple Spawn Controller..................................49 4.3.1.1 Script Breakdown................................52 4.3.2 Trigger Spawner...........................................56 4.3.3 Path Spawner..............................................57 4.3.3.1 Script Breakdown................................61 4.4 Set Gravity.........................................................66 4.5 Pretend Friction—Friction Simulation to Prevent Slipping Around........66 4.5.1 Script Breakdown..........................................68 4.6 Cameras. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 4.6.1 Third-Person Camera.......................................69 4.6.1.1 Script Breakdown................................71 4.6.2 Top-Down Camera.........................................74 4.6.2.1 Script Breakdown................................74 4.7 Input Scripts.......................................................75 4.7.1 Mouse Input...............................................75 4.7.1.1 Script Breakdown................................76 4.7.2 Single Axis Keyboard Input.................................78 4.8 Automatic Self-Destruction Script.....................................79 4.8.1 Script Breakdown..........................................79 4.9 Automatic Object Spinner............................................79 4.9.1 Script Breakdown..........................................80 ix Contents 4.10 Scene Manager.....................................................81 4.10.1 Script Breakdown..........................................82 5. Building Player Movement Controllers 85 5.1 Shoot ’Em Up Spaceship.............................................85 5.2 Humanoid Character................................................91 5.2.1 Script Breakdown..........................................96 5.3 Wheeled Vehicle...................................................106 5.3.1 Script Breakdown.........................................109 5.3.2 Wheel Alignment.........................................114 5.3.3 Script Breakdown.........................................116 6. Weapon Systems 121 6.1 Building the Scripts................................................122 6.1.1 BaseWeaponController.cs..................................122 6.1.1.1 Script Breakdown...............................127 6.1.2 BaseWeaponScript.cs......................................134 6.1.2.1 Script Breakdown...............................138 7. Recipe: Waypoints Manager 143 7.1 Waypoint System..................................................143 8. Recipe: Sound Manager 157 8.1 The Sound Controller...............................................158 8.1.1 Script Breakdown.........................................160 8.2 The Music Player...................................................163 8.2.1 Script Breakdown.........................................165 8.3 Adding Sound to the Weapons.......................................167 9. AI Manager 169 9.1 The AI State Control Script..........................................171 9.2 The Base AI Control Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .172 9.2.1 Script Breakdown.........................................185 9.3 Adding Weapon Control to the AI Controller..........................206 9.3.1 Script Breakdown.........................................210 10. Menus and User Interface 215 10.1 The Main Menu....................................................215 10.1.1 Script Breakdown.........................................223 10.2 In-Game User Interface.............................................231 x Contents 11. Dish: Lazer Blast Survival 233 11.1 Main Menu Scene..................................................235 11.2 Main Game Scene..................................................236 11.3 Prefabs...........................................................237 11.4 Ingredients........................................................238 11.5 Game Controller...................................................239 11.5.1 Script Breakdown.........................................243 11.6 Player Controller...................................................250 11.6.1 Script Breakdown.........................................253 11.7 Enemies..........................................................259 11.7.1 Script Breakdown.........................................260 11.8 Wave Spawning and Control........................................261 11.8.1 Script Breakdown.........................................263 11.9 Wave Properties...................................................265 11.10 Weapons and Projectiles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ..266 11.11 User Interface.....................................................266 11.11.1 Script Breakdown.........................................267 12. Dish: Metal Vehicle Doom 271 12.1 Main Menu Scene..................................................272 12.2 Main Game Scene..................................................272 12.2.1 Prefabs...................................................275 12.3 Ingredients........................................................275 12.3.1 Game Controller..........................................276 12.3.1.1 Script Breakdown...............................282 12.3.2 Race Controller...........................................291 12.3.2.1 Script Breakdown...............................297 12.3.3 Global Race Manager......................................306 12.3.3.1 Script Breakdown...............................311 12.3.4 Vehicle/Custom Player Control.............................318 12.3.4.1 Script Breakdown...............................327 12.3.5 User Interface.............................................344 13. Dish: Making the Game Tank Battle 345 13.1 Main Game Scene..................................................347 13.2 Prefabs...........................................................349 13.3 Ingredients........................................................349 13.4 Game Controller...................................................350 13.4.1 Script Breakdown.........................................356 13.5 Battle Controller...................................................361 13.5.1 Script Breakdown.........................................363 13.6 Global Battle Manager..............................................364 13.6.1 Script Breakdown.........................................368 13.7 Players............................................................373 13.7.1 Script Breakdown.........................................382 xi Contents 13.8 AI Chasing with SetAIChaseTargetBasedOnTag.cs.....................383 13.8.1 Script Breakdown.........................................385 14. Dish: Making the Game Interstellar Paranoids 389 14.1 Main Menu.......................................................392 14.2 Game Scenes......................................................392 14.3 Prefabs...........................................................393 14.3.1 Ingredients...............................................394 14.3.2 Game Controller..........................................395 14.3.2.1 Script Breakdown...............................401 14.3.3 Player Spaceship..........................................411 14.3.3.1 Script Breakdown...............................415 14.3.4 Enemies..................................................423 14.3.4.1 Script Breakdown...............................424 14.3.5 Waypoint Follower........................................426 14.3.5.1 Script Breakdown...............................427 Final Note 429 xiii I would like to thank my wife for all the encouragement, support, and nice cups of tea. I would also like to thank my mum and dad, my brother Steve, and everyone else who knows me. Sophie cat, be nice to the boys. Sincere thanks go to the many people who positively influence my life directly or indirectly: Michelle Ashton, Brian Robbins, George Bray, Nadeem Rasool, Christian Boutin, James and Anna, Rich and Sharon, Liz and Peter, Rob Fearon (the curator of all things shiny), everyone on Twitter who RTs my babble (you know who you are, guys!), Matthew Smith (the creator of Manic Miner), David Braben, Tōru Iwatani, and anyone who made Atari games in the 1980s. I would like to thank everyone at AK Peters/CRC Press for the help and support and for publishing my work. Finally, a massive thank you goes out to you for buying this book and for wanting to do something as cool as to make games. I sincerely hope this book helps your gamemaking adventures—feel free to tell me about them on Twitter @psychicparrot or drop by my website at http://www.psychicparrot.com. Acknowledgments xv As I was starting out as a game developer, as a self-taught programmer my skills took a while to reach a level where I could achieve what I wanted. Sometimes I wanted to do things that I just didn’t have yet the technical skills to achieve. Now and again, software packages came along that could either help me in my quest to make games or even make full games for me; complete game systems such as the Shoot ’Em-Up Construction Kit (aka SEUCK) from Sensible Software, Gary Kitchen’s GameMaker, or The Quill Adventure System could bring to life the kinds of games that went way beyond anything that my limited programming skills could ever dream of building. The downside to using game creation software was that it was tailored to create games within their chosen specific genre. If I wanted to do something outside of the limitations of the software, the source code was inaccessible and there was no way to extend or modify it. When that happened, I longed for a modular code-based system that I could plug together to create different types of games but modify parts of it without having to spend a lot of time learning how the entire system internals work—building block game development that I could actually script and modify if I needed to. After completing my first book, Game Development for iOS with Unity3D, I wanted to follow up by applying a modular style of game building to Unity3D that would provide readers with a highly flexible framework to create just about any kind of game by “plugging in” the different script components. My intention was to make a more technical second book, based on C# programming, that would offer extensibility in any direction a developer might require. In essence, what you are holding in your hands right now is a cookbook Introduction xvi Introduction for game development that has a highly flexible core framework for just about any type of game. A lot of the work I put in at the start of writing this book was in designing a framework that not only made sense in the context of Unity but also could easily cope with the demands of different genres. Prerequisites You can get up and running with the required software for the grand total of zero dollars. Everything you need can be downloaded free of charge with no catches. You may want to consider an upgrade to Unity Pro at some point in the future, to take advantage of some of its advanced features, but to get started all you need to do is grab the free version from the Unity website. Unity Free or Unity Pro (available from the Unity store at http://www.unity3d.com) Unity Free is completely free for anyone or any company making less than $100,000 per year—it may be downloaded for no charge at all, and you don’t even need a credit card. It’s a really sweet deal! We are talking about a fully functional game engine, ready to make 3D or 2D games that may be sold commercially or otherwise. There are no royalties to pay, either. Unity Pro adds a whole host of professional functionality to the engine, such as render culling and profiling. If you are a company with more than $100,000 per year of turnover, you will need a Pro license, but if you find that Unity Free doesn’t pack quite enough power, you may also want to consider going Pro. You can arrange a free trial of the Pro version right from the Unity website to try before you buy. If the trial licence runs out before you feel you know enough to make a purchase, contact Unity about extending it and they are usually very friendly and helpful about it (just don’t try using a trial license for 6 months at a time, as they may just figure it out!). C# programming knowledge Again, to reiterate this very important point, this is nota book about learning how to program. You will need to know some C#, and there are a number of other books out there for that purpose, even if I have tried to make the examples as simple as possible! This book is about making games, not about learning to program. What This Book Doesn’t Cover This is not a book about programming and it is not a book about the right or wrong way to do things. We assume that the reader has some experience with the C# programming language. I am a self-taught programmer, and I understand that there may well be better ways to do things. xvii Introduction This is a book about concepts, and it is inevitable that there will be better methods for achieving some of the same goals. The techniques and concepts offered in this book are meant to provide solid foundation, not to be the final word on any subject. It is the author’s intention that, as you gain your own experiences in game development, you make your own rules and draw your own conclusions. Additional material is available from the CRC Press Web site: http://www.crcpress. com/product/isbn/9781466581401. 1 1 Making Games the Modular Way When I first started making games, I would approach development on a project-to-project basis, recoding and rebuilding everything from scratch each time. As I became a professional developer, landing a job at a game development studio making browser-based games, I was lucky enough to work with a guy who was innovating the scene. He was a master at turning out great games (both visually and gameplay-wise) very quickly. One secret to his success lay in the development of a reusable framework that could easily be refactored to use on all of his projects. His framework was set up to deal with server communication, input handling, browser communication, and UI among other things, saving an incredible amount of time in putting together all of the essentials. By reusing the framework, it allowed more time for him and his team to concentrate on great gameplay and graphics optimization, resulting in games that, at the time, blew the competition away. Of course, the structure was tailored to how he worked (he did build it, after all), and it took me a while to get to grips with his style of development; but once I did, it really opened my eyes. From then on, I used the framework for every project and even taught other programmers how to go about using it. Development time was substantially reduced, which left more time to concentrate on making better games. This book is based on a similar concept of a game-centric framework for use with many different types of games, rather than a set of different games in different styles. The overall goal of this book is to provide script-based components that you can use within that framework to make a head start with your own projects in a way that reduces recoding, repurposing, or adaptation time. 2 1. Making Games the Modular Way In terms of this book as a cookbook, think of the framework as a base soup and the scripting components as ingredients. We can mix and match script components from different games that use the same framework to make new games, and we can share several of the same core scripts in many different games. The framework takes care of the essentials, and we add a little “glue” code to pull everything together the way we want it all to work. This framework is, of course, optional, but you should spend some time familiarizing yourself with it to help understand the book. If you intend to use the components in this book for your own games, the framework may serve either as a base to build your games on or simply as a tutorial test bed for you to rip apart and see how things work. Perhaps you can develop a better framework or maybe you already have a solid framework in place. If you do, find a way to develop a cleaner, more efficient framework or even a framework that isn’t quite so efficient but works better with your own code, and do it. In this chapter, we start by examining some of the major programming concepts used in this book and look at how they affect the design decisions of the framework. 1.1 Important Programming Concepts I had been programming in C# for a fairly long time before I actually sat down and figured out some of the concepts covered in this chapter. It was not because of any particular problem or difficulty with the concepts themselves but more because I had solved the problems in a different way that meant I had no real requirement to learn anything new. For most programmers, these concepts will be second nature and perhaps something taught in school, but I did not know how important they could be. I had heard about things like inheritance, and it was something I put in the to-do list, buried somewhere under “finish the project.” Once I took the time to figure them out, they saved me a lot of time and led to much cleaner code than I would have previously pulled together. If there’s something you are unsure about, give this chapter a read-through and see whether you can work through the ideas. Hopefully, they may save some of you some time in the long run. 1.1.1 Manager and Controller Scripts I am a strong believer in manager and controller scripts. I like to try and split things out into separate areas; for example, in the Metal Vehicle Doomgame, I have race controller scripts and a global race controller script. The race controller scripts are attached to the players and track their positions on the track, waypoints, and other relevant player-specific race information. The global race controller script talks to all the race controller scripts attached to the players to determine who is winning and when the race starts or finishes. By keeping this logic separate from the other game scripts and contained in their own controller scripts, it makes it easier to migrate them from project to project. Essentially, I can take the race controller and global race controller scripts out of the game and apply them to another game, perhaps one that features a completely different type of gameplay— for example, alien characters running around a track instead of cars. As long as I apply the correct control scripts, the race logic is in place, and I can access it in the new game. In the framework that this book contains, there are individual manager and controller scripts dealing with user data, input, game functions, and user interface. We look at those in detail in Chapter 2, but as you read this chapter, you should keep in mind the idea of separated scripts dedicated to managing particular parts of the game structure. It was 3 1.1 Important Programming Concepts important to me to design scripts as standalone so that they may be used in more than one situation. For example, our weapon slot manager will not care what kind of weapon is in any of the slots. The weapon slot manager is merely an interface between the player and the weapon, taking a call to “fire” and responding to it by telling the weapon in the currently selected weapon slot to fire. What happens on the player end will not affect the slot manager just as anything that happens with the weapon itself will not affect the slot manager. It just doesn’t care as long as your code talks to it in the proper way and as long as your weapons receive commands in the proper way. It doesn’t even matter what type of object the slot manager is attached to. If you decide to attach the weapon slot manager to a car, a boat, a telegraph pole, etc., it doesn’t really matter just as long as when you want them to fire, you use the correct function in the slot manager to get it to tell a weapon to fire. Since our core game logic is controlled by manager and controller scripts, we need to be a little smart about how we piece everything together. Some manager scripts may benefit from being static and available globally (for all other scripts to access), whereas others may be better attached to other scripts. We deal with these on a case-by-case basis. To get things started, we will be looking at some of the ways that these manager scripts can communicate with each other. As a final note for the topic in this section, you may be wondering what the difference is between managers and controllers. There really isn’t all that much, and I have only chosen to differentiate for my own sanity. I see controllers as scripts that are larger global systems, such as game state control, and managers as smaller scripts applied to gameObjects, such as weapon slot management or physics control. The terms are applied loosely, so don’t worry if there appear to be inconsistencies in the application of the term in one case versus another. I’ll try my best to keep things logical, but that doesn’t mean it’ll always make sense to everyone else! 1.1.2 Script Communication An important part of our manager- and component-based structures is how our scripts are going to communicate with each other. It is inevitable that we will need to access our scripts from a multitude of other areas of the game, which means we should try to provide interfaces that make the most sense. There are several different ways of communicating between scripts and objects in Unity: 1. Direct referencing manager scripts via variables set in the editor by the Inspector window. The easiest way to have your scripts talk to each other is to have direct references to them in the form of public variables within a class. They are populated in the Unity editor with a direct link to another script. Here is an example of direct referencing: public void aScript otherScript; In the editor window, the Inspector shows the otherScript field. We drag and drop an object containing the script component that we want to talk to. Within the class, function calls are made directly on the variable, such as otherScript.DoSomething(); 4 1. Making Games the Modular Way 2. GameObject referencing using SendMessage. SendMessage is a great way to send a message to a gameObject and call a function in one of its attached scripts or components when we do not need any kind of return result. For example, SomeGameObject.SendMessage("DoSomething"); SendMessage may also take several parameters, such as setting whether or not the engine should throw an error when there is no receiver, that is, no function in any script attached to the gameObject with a name matching the one in the SendMessage call. (SendMessageOptions). You can also pass one parameter into the chosen function just as if you were passing it via a regular function call such as SomeGameObject.SendMessage("AddScore",2); SomeGameObject.SendMessage("AddScore", SendMessageOptions.RequireReceiver); SomeGameObject.SendMessage("AddScore", SendMessageOptions.DontRequireReceiver); 3. Static variables. The static variable type is useful in that it extends across the entire system; it will be accessible in every other script. This is a particularly useful behavior for a game control script, where several different scripts may want to communicate with it to do things such as add to the player’s score, lose a life, or perhaps change a level. An example declaration of a static variable might be private static GameController aController; Although static variables extend across the entire program, you can have private and public static variables. Things get a little tricky when you try to understand the differences between public and private static types—I was glad to have friends on Twitter that could explain it all to me, so let me pass on what I was told: Public static A public static variable exists everywhere in the system and may be accessed from other classes and other types of script. Imagine a situation where a player control script needs to tell the game controller script whenever a player picks up a banana. We could deal with it like this: 1. In our gamecontroller.cs game controller script, we set up a public static: public static GameController gateway; 2. When the game controller (gamecontroller.cs) runs its Start() function, it stores a reference to itself in a public static variable like this: gateway = this; 3. In any other class, we can now access the game controller by referring to its type followed by that static variable (GameController.gateway) such as GameController.gateway.GotBanana(); 5 1.1 Important Programming Concepts Private static A private static variable exists within the class it was declared and in any other instances of the same class. Other classes/types of script will not be able to access it. As a working example, try to imagine that a script named player.cs directly controls player objects in your game. They all need to tell a player manager script when something happens, so we declare the player manager as a static variable in our player.cs script like this: private static PlayerManager playerManager; The playerManager object only needs to be set up once, by a single instance of the player class, to be ready to use for all the other instances of the same class. All player.cs scripts will be able to access the same instance of the PlayerManager. 4. The singleton design pattern. In the previous part of this section, we looked at using a static variable to share a manager script across the entire game code. The biggest danger with this method is that it is possible to create multiple instances of the same script. If this happens, you may find that your player code is talking to the wrong instance of the game controller. A singletonis a commonly used design pattern that allows for only one instance of a particular class to be instantiated at a time. This pattern is ideal for our game scripts that may need to communicate (or be communicated with) across the entire game code. Note that we will be providing a static reference to the script, exactly as we did in the “Static Variables” method earlier in this section, but in implementing a singleton class, we will be adding some extra code to make sure that only one instance of our script is ever created. 1.1.3 Using the Singleton Pattern in Unity It is not too difficult to see how useful static variables can be in communication between different script objects. In the public static example cited earlier, the idea was that we had a game controller object that needed to be accessed from one or more other scripts in our game. The method shown here was demonstrated on the Unity public wiki*by a user named Emil Johansen (AngryAnt). It uses a private static variable in conjunction with a public static function. Other scripts access the public function to gain access to the private static instance of this script, which is returned via the public function so that only one instance of the object will ever exist in a scene regardless of how many components it is attached to and regardless of how many times it is instantiated. A simple singleton structure: public class MySingleton { private static MySingleton instance; public MySingleton () *http://wiki.unity3d.com/index.php/Singleton. 6 1. Making Games the Modular Way { if (instance != null) { Debug.LogError ("Cannot have two instances of singleton."); return; } instance = this; } public static MySingleton Instance { get { if (instance == null) { new MySingleton (); } return instance; } } } The singleton instance of our script may be accessed anywhere, by any script, simply with the following syntax: MySingleton.Instance.MySingletonMember; 1.1.4 Inheritance Inheritanceis a complex concept, which demands some explanation here because of its key role within the scripts provided in this book. Have a read through this section, but don’t worry if you don’t pick up inheritance right away. Once we get to the programming, it will most likely become clear. The bottom line is that inheritance is used in programming to describe a method of providing template scripts that may be overridden, or added to, by other scripts. As a metaphor, imagine a car. All cars have four wheels and an engine. The types of wheels may vary from car to car, as will the engine, so when we say “this is a car” and try to describe how our car behaves, we may also describe the engine and wheels. These relationships may be shown in a hierarchical order: Car -Wheels -Engine Now try to picture this as a C# script: Car class Wheels function Engine function 7 1.1 Important Programming Concepts

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧